我编写了一个代码来测试,以测试Linux和Windows操作系统的内存管理.为了进一步测试,我继续检查malloc()返回的内存中存在哪些值.
返回的值都是0(零).我已经阅读了malloc的手册页,在Windows和Linux上都进行过检查,但是我无法找到这种行为的原因.根据联机帮助页
malloc()函数分配大小字节并返回指向已分配内存的指针.内存未初始化.
要清除内存段,必须手动使用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");
}
}
Run Code Online (Sandbox Code Playgroud)
也许我错过了什么.代码从这里改编
编辑:这里 已经回答了GCC特定输出的问题.我相信Windows操作系统也会遵循相同的程序.
我正在编写一个c程序来进行一些计算.如果我能够通过点击鼠标获得响应,那真的会对我有所帮助.
我怎么能这样做如果不可能那么使用C的哪些功能或库我将能够做到这一点.