简体   繁体   English

为什么在运行malloc代码之前分配内存?

[英]Why is memory being allocated before malloc code has run?

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). 使用gcc 4.4.5进行编译,并在第一个暂停和第二个暂停运行top -p <pid>在我们正在使用的VM(ubuntu 10.10)中的系统上产生相同的输出。 Is this a compiler or OS optimization, or is something else going on? 这是编译器或OS优化,还是其他事情?

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. 例如,请参见http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory/

What you are seeing is the initial heap allocation to the process, not the total memory allocated by the process from that heap. 您将看到的是对进程的初始堆分配,而不是该进程从该堆分配的总内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM