I am currently working on a NUMA machine. I am using numa_free
to free my allocated memory. However, unlike free
, numa_free
needs to know how many bytes are to be freed. Is there any way to know that how many bytes are pointed to by a pointer without tracing it out?
相关问题
- Multiple sockets for clients to connect to
- Do the Java Integer and Double objects have unnece
- What uses more memory in c++? An 2 ints or 2 funct
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
There is no way to obtain memory size using underlying API. You must remember size during the allocation somewhere. For Example, You may write your own allocator, that allocates 4 extra bytes, stores in first 4 bytes size of buffer, and during deallocation you can read size of buffer from it:
Store the allocation size just before the memory pointer reported.
@light_keeer has a good solution/approach, yet suffers from potential alignment problems @pdw.
my2_alloc()
, likemalloc()
, presumably returns a pointer that meets alignment requirements of the C spec. Likewise,my2_alloc()
also needs to insure the returned pointer meets alignment requirements.Follows is a candidate C99 solution.
If you allocated memory for a single value, you probably used
sizeof()
to find the amount of space needed for that value's type. You should know what that type was, too, because it's the type of the pointer. So you can just callsizeof()
again on the same type. (For example, if you allocatedsizeof(Foo)
bytes to store into aFoo*
, then you want to freesizeof(Foo)
bytes as well.)If you allocated memory for an array, you should already be keeping track of the length of that array, e.g. so that you know where to stop when iterating. Multiply that length by the size of the individual element type.
A pointer just indicates a distinct point in memory, which is usually where your data starts. It is always up to the developer to keep track of how much space has been made available at that location. (
free
is an exception to the rule).