0

OBJECTIVE: manage a unsigned long tomBOLA[5][10000000];

$top gives me:

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

program has, a malloc the size of (5*10000000) * 8bytes =382MB, then fill with 0s and a read of what is stored in 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 gives

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) 

about memory, what am i doing or assuming wrong ??

4

3 回答 3

7

这个:

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

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

tomBOLA = malloc(5 * sizeof *tomBOLA);

获得五个指向unsigned long.

请注意,动态执行此操作没有意义,只需说:

unsigned long *tomBOLA[5];

还:

  1. 摆脱malloc()'s 返回值的强制转换。
  2. 停止使用神奇的常量(上面的解决方案使5其余代码中的消失,因为您可以使用sizeof tomBOLA / sizeof *tomBOLA代替5)。
于 2013-05-14T13:35:10.410 回答
2

你的第一个 malloc 是错误的。您需要为指针分配足够的内存。

if((tomBOLA=(long int **)malloc(5))==NULL){ /*MALLOC()*/

应该

if((tomBOLA=(long int **)malloc(5 * sizeof *tomBOLA))==NULL){ /*MALLOC()*/

sizeof *tomBOLA此处与sizeof(long int *)本例相同,但遵循 的一般模式SomeType *p = malloc(sizeof *p)

于 2013-05-14T13:37:05.360 回答
0

您很可能拥有可用的内存,但不是在 malloc 调用试图为您提供的连续块中。

于 2013-05-14T13:34:10.867 回答