【发布时间】:2015-05-07 01:47:51
【问题描述】:
我写了一个代码来测试Linux和Windows操作系统的内存管理压力测试。为了进一步测试,我继续检查了 malloc() 返回的内存中存在哪些值。
返回的值都是 0(零)。我已经阅读了 malloc 的手册页,在 Windows 和 Linux 上都进行了检查,但我 不能找出这种行为的原因。根据手册页的
malloc() 函数分配 size 字节并返回一个指向已分配内存的指针。内存未初始化。
要清除内存段,必须手动使用 memset()。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int eat(long total,int chunk){
long i;
for(i=0;i<total;i+=chunk){
short *buffer=malloc(sizeof(char)*chunk);
if(buffer==NULL){
return -1;
}
printf("\nDATA=%d",*buffer);
memset(buffer,0,chunk);
}
return 0;
}
int main(int argc, char *argv[]){
int i,chunk=1024;
long size=10000;
printf("Got %ld bytes in chunks of %d...\n",size,chunk);
if(eat(size,chunk)==0){
printf("Done, press any key to free the memory\n");
getchar();
}else{
printf("ERROR: Could not allocate the memory");
}
}
也许我错过了什么。 代码改编自here
编辑: GCC 特定输出的问题已得到回答here。我相信 Windows 操作系统也会遵循相同的程序。
【问题讨论】:
标签: c linux memory memory-management malloc