Heap Memory Example
For the execution of this program fragment:
int *p, *arr;
char *c_arr;
p = (int *)malloc(sizeof(int));
arr = (int *)malloc(sizeof(int)*20);
c_arr = (char *)malloc(sizeof(char)*10);
if((p == NULL) || (arr == NULL) || (c_arr == NULL)) {
printf("malloc error\n");
exit(1);
}
*p = 6;
*arr = 8;
arr[3] = 10;
strcpy(c_arr, "He");
c_arr[1] = 'i';
The contents of memory will look like this:
STACK HEAP
|===============| |====================================|
main: | | | |
| ---- | | ---- |
| p | *-------------------------->| 6 | |
| ---- | | ---- |
| ---- | | ------------------------- |
| arr | *-------------------------->| 8 | ? | ? | 10 | ? |...| |
| ---- | | ------------------------- |
| ---- | | ------------------------- |
| c_arr | *-------------------------->| 'H' | 'i' | '\0' | ...| |
| ---- | | ------------------------- |
|===============| |====================================|