Reputation: 93
For a project, we have to write a simple program which spawns a child thread, prints top output in batch, has the child thread allocate some memory, and prints the top output again. Intuitively, there should be a difference in the top output between the two states, as memory is being allocated between them. However, in all my testing, it seems that the memory that the child thread allocates is already allocated when the child thread is spawned, so there is no difference between the top outputs.
I do see a difference if I allocate more memory than the amount specified in the project, but my professor said there should be a difference with the given amount. Also, I see a difference if the memory is allocated in the main thread, but when the allocation code is moved to a child thread, all the memory is allocated at the point when the child thread is created. Here is a simpler program which reproduces the issue:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void * allocate_memory(void * param) {
getchar();
malloc(4096 * 4);
malloc(4096 * 4);
malloc(4096 * 4);
malloc(4096 * 4);
getchar();
}
int main (int argc, char *argv[]) {
pthread_t child;
printf("PID: %d\n",getpid());
pthread_create(&child, NULL, &allocate_memory, NULL);
pthread_join(child, NULL);
}
Compiling with gcc 4.4.5 and running top -p <pid>
at the first pause and the second pause yields the same output on the system in the VM we're using (ubuntu 10.10). Is this a compiler or OS optimization, or is something else going on?
Upvotes: 0
Views: 80
Reputation: 93466
An initial heap is allocated to the process by the OS when the process is loaded; if an allocation cannot be satisfied the heap is extended by requesting more memory from the operating system.
See http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory/ for an explanation for example.
What you are seeing is the initial heap allocation to the process, not the total memory allocated by the process from that heap.
Upvotes: 2