Allocating proper memory size
-
29-04-2021 - |
Question
I am having an issue with allocating the right size of memory in my program. I do the following:
void * ptr = sbrk(sizeof(void *)+sizeof(unsigned int));
When I do this, I think it is adding too much memory to the heap because it is allocating it in units of void* instead of bytes. How do I tell it that I want sizeof(whatever) to mean whatever bytes instead of whatever other units?
EDIT:
I have seen other people cast things as a char so that the compiler takes the size in bytes. If sizeof(unsigned int) is 4 bytes, but the type that I was using is void *, will the compiler break 4 times the size of a void * instead of 4 bytes?
Solution
Pass a number of bytes as the argument of sbrk
.
In Linux, the prototype of sbrk
is:
void *sbrk(intptr_t increment);
http://www.kernel.org/doc/man-pages/online/pages/man2/brk.2.html
sbrk() increments the program's data space by increment bytes.
But as some people in the comments added, if you want to dynamically allocate memory you are looking for the malloc
function and not sbrk
. brk
and sbrk
are syscalls that are usually used internally for the implementation of the malloc
user function.
OTHER TIPS
The kernel manages process memory in a page granularity. This means the process address space must grow (or shrink) by a whole number of pages.
So even though sbrk
gets a number of bytes, it would add at least one page to the process.