目标:管理aunsigned long tomBOLA[5][10000000];
$top给我:

top - 14:05:35 up  4:06,  4 users,  load average: 0.46, 0.48, 0.44
Tasks: 182 total,   1 running, 180 sleeping,   1 stopped,   0 zombie
Cpu(s): 14.4%us,  2.4%sy,  0.0%ni, 82.5%id,  0.6%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:   3092064k total,  1574460k used,  1517604k free,   168944k buffers
Swap:  1998840k total,        0k used,  1998840k free,   672756k cached

程序有一个大小为(5*10000000)*8bytes=382MB的malloc,然后填充0并读取存储在tomBOLA中的内容:
long int **tomBOLA;

if((tomBOLA=(long int **)malloc(5))==NULL){ /*MALLOC()*/
    printf("\n\tMEMORY ERROR-1");
    exit(1);
}
for(i=0;i<5;i++){
    if((tomBOLA[i]=(long int *)malloc(10000000*sizeof(long int)))==NULL){
        printf("\n\tMEMORY ERROR-2");
        exit(1);
    }
}                                          /*MALLOC()*/
for(i=0;i<5;i++){
    for(j=0;j<10000000;j++){
        tomBOLA[i][j]=0;
    }
}                                         /*FILL WITH 0s before using*/
for(i=0;i<5;i++){
    for(j=0;j<10000000;j++){
        printf("%ld ",tomBOLA[i][j]);
    }
printf("\n\n\n\n\n");
}                                         /*CONTROL OF 0s*/

gdb给予
Program received signal SIGSEGV, Segmentation fault.
_int_malloc (av=<value optimized out>, bytes=<value optimized out>) at malloc.c:4708
4708    malloc.c: No such file or directory.
    in malloc.c
(gdb) bt
#0  _int_malloc (av=<value optimized out>, bytes=<value optimized out>) at malloc.c:4708
#1  0x001dfd4c in *__GI___libc_malloc (bytes=40000000) at malloc.c:3660
#2  0x0804ca86 in main ()
(gdb)

关于记忆,我做错了什么??

最佳答案

这:

tomBOLA=(long int **)malloc(5))

错误的是,它分配了5个字节,当您将其视为5个指针的数组(可能需要20个字节)时,会导致立即的缓冲区溢出。你的意思是:
tomBOLA = malloc(5 * sizeof *tomBOLA);

获得指向unsigned long的五个指针。
注意,动态地这样做没有意义,简单地说:
unsigned long *tomBOLA[5];

也:
Get rid of the casts of malloc()'s return value
停止使用神奇的常量(上面的解决方案使5在代码的其余部分消失,因为您可以使用sizeof tomBOLA / sizeof *tomBOLA代替5)。

07-25 22:28