Reputation: 133
Consider the following code:
int *p = malloc(4);
int *i = malloc(4);
Now, a chunk of memory (4 bytes in the above situation) has been allocated and the base address is stored in p
.
While allocating the memory in the line int *i = malloc(4)
.
How does the compiler come to know that this chunk of memory is allocated?
Why is it not allocating the same chunk of memory that has been allocated with int *p = malloc(4)
?
Upvotes: 0
Views: 132
Reputation: 1913
The compiler is not responsible for knowing who has what piece of memory and not accidentally trampling over previous allocated memory. This is a the job of the operating system. The compiler generates assembly code where in the assembly code makes the appropriate system calls to get a pointer to a piece of dynamic memory from the OS. To demonstrate, here's a silly example:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int* ptr = malloc(4);
free(ptr);
return 0;
}
Now when that program is compiled and main
is disassembled, the assembly code looks something like:
0x0000000100000f50 <+0>: push %rbp
0x0000000100000f51 <+1>: mov %rsp,%rbp
0x0000000100000f54 <+4>: sub $0x10,%rsp
0x0000000100000f58 <+8>: mov $0x4,%eax
0x0000000100000f5d <+13>: mov %eax,%edi
0x0000000100000f5f <+15>: movl $0x0,-0x4(%rbp)
0x0000000100000f66 <+22>: callq 0x100000f8a
0x0000000100000f6b <+27>: mov %rax,-0x10(%rbp)
0x0000000100000f6f <+31>: mov -0x10(%rbp),%rax
0x0000000100000f73 <+35>: mov %rax,%rdi
0x0000000100000f76 <+38>: callq 0x100000f84
0x0000000100000f7b <+43>: xor %eax,%eax
0x0000000100000f7d <+45>: add $0x10,%rsp
0x0000000100000f81 <+49>: pop %rbp
0x0000000100000f82 <+50>: retq
Notice the callq
line. The compiler is just responsible for calling the appropriate system calls to get dynamic memory.
Upvotes: 1
Reputation: 224310
When you use routines like malloc
in your code and and compile and link your code into an executable program, a library of software routines is linked into your code too. The routines in that library have software for requesting memory from the operating system, for dividing that memory into parts and giving it out when requested with malloc
, and for keeping track of what has been given out and what has been released with free
.
So, whenever you compile a very small program, you get along with it a large library of additional software that people have worked on for many years.
Upvotes: 2