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 ?
intarray allocated by malloc and any other int array.