0

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?

mrswmmr
  • 2,081
  • 5
  • 21
  • 23
  • Can you clarify why you're adding in `sizeof(void*)` here? What are you planning on doing with this memory? Also, any reason that you're not using plain-ol' `malloc` here? – templatetypedef Feb 13 '12 at 21:14
  • 5
    Short answer: Either you know what you're doing and you don't need to ask this question, or you *don't* know what you're doing and you shouldn't use `sbrk()`, but rather `malloc()`. – Kerrek SB Feb 13 '12 at 21:15
  • I am avoiding malloc because I am experimenting with some of the system calls (such as sbrk()), and I am trying to store a pointer of any type and an unsigned integer in this block of memory that I added to the heap – mrswmmr Feb 13 '12 at 21:16
  • Just to be clear, the `sizeof` operator returns the size in bytes. I don't understand what you're asking. Have you tried printing the resulting size to check if it's what you're expecting? – jweyrich Feb 13 '12 at 21:18
  • I trust you know what you are doing and realise that using this in place of malloc will degrade the performance of your program – David Heffernan Feb 13 '12 at 22:10

2 Answers2

0

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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • so sbrk will only ever take its arguments in bytes? I seem to remember that the type of whatever memory you are allocating affects the size of either sbrk or malloc – mrswmmr Feb 13 '12 at 21:19
  • @mrswmmr the Linux `sbrk` function and the Standard `malloc` function take a number of bytes as their operand, – ouah Feb 13 '12 at 21:22
0

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.

ugoren
  • 16,023
  • 3
  • 35
  • 65