0

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 ?

1
  • This is not how arrays work. There's no difference in accessing an int array allocated by malloc and any other int array. Commented Feb 3, 2023 at 8:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 ?

There are several misunderstandings in your interpretation of the use of malloc that make your code incorrect:

  • malloc is a generic library routine that needs as parameter the amount of bytes to allocate and you correctly ask for space for 24356 cells by the size of one cell (64 bytes) or 1,558,784 bytes. (Around 1,5Mb, and not the 190kb you say in the question)
  • Then, you access the array elements by byte offset, this time erroneusly, as you have defined an array of structs, you cannot get the 24,356 (and later) array elements.

The expression you use inside the array index can range only from 0 to 24355, and no more.

Change

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

by

nd[i].n1 = i;

As arrays must be indexed by element position, and not by element address (respect to array origin)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.