I can't figure out why this 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;
for (j=0;j<in;j++)
n[j] = j;
printf("Sanity check...\n");
char *c = (char *)malloc(1024*1024*20);
int i;
for (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 I move one of the for-loops down like 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;
for (i=0; i<20*1024*1024;i++)
c[i] = i;
printf("No segfault. Yay!\n");
for (j=0;j<in;j++)
n[j] = j;
return 0;
}
everything works.. same compilation step, this is the output:
$ ./run 1000
$ Input 1000
$ Sanity check...
$ No segfault. Yay!
Reason why I'm doing a large 20MB malloc is to try and remove cache effects from the code I am profiling. It feels like both implementations should work, but the first one segfaults when malloc-ing the 20MB array. Am I missing something 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)
is 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With