I'm new to linux programming and i want to know is it possible to increase the heap size of a running process. If it is possible, please help me how to do it right. Thanks anyone for helping.
-
1yes, just allocate more memory – Iłya Bursov Mar 10 '18 at 18:24
-
2Possible duplicate of [What and where are the stack and heap?](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) – Mohammad Kanan Mar 10 '18 at 18:25
2 Answers
Heap is just memory. There is nothing special about it. Any memory can become heap. Diagrams showing a heap area are pedagogical, rather than real.
"Heap" is is "Heap" only because the memory is allocated by a heap manager. While most programs only have on heap manager, it is possible to have multiple heap managers.
Thus heap size is controlled by a heap manager. Most simple heap managers give the user no control over the heap size. The heap manager allocates more memory when it needs memory to respond to allocation calls.
Some heap managers give the user function calls to allow him to allocate an expand the heap size.

- 20,574
- 3
- 26
- 62
Just use a function like malloc()
or calloc()
to allocate memory dynamically. To deallocate the memory and return it to the heap, use free()
. These functions will manage the size of the heap by expanding or shrinking it as needed.
Example:
Everything in heap is anonymous. You can't access the memory directly. Every access is indirect. So store the address of allocated memory returned by malloc()
in a pointer.
int *ptr = malloc(sizeof(int));
We can use *ptr
to access the memory's contents.
*ptr = 3;
printf("%d", *ptr);
Once you are done using the memory. You deallocate it with
free(ptr);
According to Peter van der Linden's book on C programming,
The end of the heap is marked by a pointer known as the "break". When the heap manager needs more memory, it can push the break further away using the system calls
brk
andsbrk
.You typically don't call
brk
yourself explicitly, but if youmalloc
enough memory,brk
will eventually be called for you.Your program may not call both
malloc()
andbrk()
. If you usemalloc
,malloc
expects to have sole control over whenbrk
andsbrk
are called.
The limit on the maximum size of heap is determined by the size of virtual memory of the system.
Here's a crude reproduction of the image:
-
1The picture is really naive and actually wrong in 2018. Try `cat /proc/$$/maps` – Basile Starynkevitch Mar 10 '18 at 19:50