Why does this segfault in C? -
i can't figure out why tiny c program segfaults:
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]){ int in = atoi(argv[1]); printf("input %d\n",in); int *n = (int *)malloc(in); int j; (j=0;j<in;j++) n[j] = j; printf("sanity check...\n"); char *c = (char *)malloc(1024*1024*20); int i; (i=0; i<20*1024*1024;i++) c[i] = i; printf("no segfault. yay!\n"); return 0; } compiled with:
$ gcc -o0 test.c -o run
output:
$ ./run 1000
$ input 1000
$ sanity check...
$ [1] 17529 segmentation fault (core dumped) ./run 1000
now if move 1 of for-loops down this:
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]){ int in = atoi(argv[1]); printf("input %d\n",in); int *n = (int *)malloc(in); int j; printf("sanity check...\n"); char *c = (char *)malloc(1024*1024*20); int i; (i=0; i<20*1024*1024;i++) c[i] = i; printf("no segfault. yay!\n"); (j=0;j<in;j++) n[j] = j; return 0; } everything works.. same compilation step, output:
$ ./run 1000
$ input 1000
$ sanity check...
$ no segfault. yay!
reason why i'm doing large 20mb malloc try , remove cache effects code profiling. feels both implementations should work, first 1 segfaults when malloc-ing 20mb array. missing obvious here?
thanks.
int in = atoi(argv[1]); int *n = (int *)malloc(in); you're allocating in bytes, not in integers. try:
malloc(sizeof(int) * in); your second allocation works because sizeof(char) 1.
Comments
Post a Comment