Home > Software engineering >  Getting segmentation fault when accessing memory allocated by malloc()
Getting segmentation fault when accessing memory allocated by malloc()

Time:02-04

I have the following code snippet, which is giving me segmentation fault.

#include <stdio.h>
#include <stdlib.h>

struct node {
    unsigned int n1;
    unsigned int n2;
};

int main() {
    struct node *nd = (struct node *)malloc(24356 * sizeof(struct node));
    for(int i=0; i < 24356; i  ) {
        nd[i * sizeof(struct node)].n1 = i;
        nd[i * sizeof(struct node)].n2 = i 1;
    }       
    return 0;
}

When I did some debugging, I could find that the for loop was executing for some 3000 times, and then the segmentation fault occurs on this line:

nd[i * sizeof(struct node)].n1 = i;

I couldn't understand what is wrong in this code. Can't malloc() allocate the amount of memory (~190 KB) I am asking it to allocate ? If so, why doesn't it return NULL ?

CodePudding user response:

These lines are the problem:

nd[i * sizeof(struct node)].n1 = i;
nd[i * sizeof(struct node)].n2 = i 1;

Change them to:

nd[i].n1 = i;
nd[i].n2 = i 1;

Remember, indices are not byte offesets. They're element indices. The compiler will automatically scale them by the size of an element.

  • Related