I can't understand why this tiny C segfaults program:
#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
Conclusion:
$. / run 1000
$ Entrance 1000
$ Health Check ...
$ [1] 17529 Segmentation error (kernel reset) ./ run 1000
Now, if I moved one of the for-loops loops 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 build phase, this is the conclusion:
$. / run 1000
$ Entrance 1000
$ Health Check ...
$ No segfault. Hooray!
The reason I am making a large 20 megabyte malloc is to try to remove the cache effects from the code that I am profiling. It looks like both implementations should work, but the first one works when the malloc-ing array is 20MB. Did I miss something obvious here?
Thank.
source
share