Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this segfault in C?

Tags:

c

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.

like image 429
sidmontu Avatar asked Nov 28 '22 07:11

sidmontu


1 Answers

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.

like image 96
John Ledbetter Avatar answered Dec 15 '22 06:12

John Ledbetter