Vivek
Vivek

Reputation: 2020

struct pointer always getting initialized to nil

I am having this problem where my struct pointer is always getting initialized to nil by default. Below is my code.

#include <stdio.h>

struct SomeStruct {
    int x;
};

int main()
{
    int array[2];  // If I change this to 1, the code works fine

    struct SomeStruct *ptr;
    printf("%p\n", ptr);  // always prints "nil"
}

Can someone please explain what is going on here. Specifically, why does changing the size of array to 1 make the code run fine.

The above was part of some larger code and I was able to simplify the problem to this. I need to use ptr later but I get segmentation faults as it is nil.

Upvotes: 0

Views: 66

Answers (2)

cnicutar
cnicutar

Reputation: 182744

Can someone please explain what is going on here. Specifically, why does changing the size of array to 1 make the code run fine.

You're using ptr without initializing it. Changing the size of the array changes the layout of the stack and your code executes "fine" by luck.

I need to use ptr later but I get segmentation faults as it is nil

Then assign some memory to it:

ptr = malloc(sizeof *ptr);

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272762

You are accessing an uninitialised variable, so you are relying on undefined behaviour; the result could be anything.

In practice, you are seeing an artefact of whatever rubbish happens to be on your stack when your program runs.

Upvotes: 1

Related Questions