c - why cant i manage ~382MB of memory when i have it available? -
objective: manage unsigned long tombola[5][10000000];
$top
gives me:
top - 14:05:35 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, malloc size of (5*10000000) * 8bytes =382mb, fill 0s , read of 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 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>) @ 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>) @ malloc.c:4708 #1 0x001dfd4c in *__gi___libc_malloc (bytes=40000000) @ malloc.c:3660 #2 0x0804ca86 in main () (gdb)
about memory, doing or assuming wrong ??
this:
tombola=(long int **)malloc(5))
is wrong, it's allocating 5 bytes, leading immediate buffer overrun when treat array of 5 pointers (needing 20 bytes). meant:
tombola = malloc(5 * sizeof *tombola);
to 5 pointers unsigned long
.
note there's no point in doing dynamically, it's way simpler say:
unsigned long *tombola[5];
also:
- get rid of casts of
malloc()
's return value. - stop using magical constants (the solution above makes
5
go away in rest of code, since can usesizeof tombola / sizeof *tombola
in place of5
).
Comments
Post a Comment