Search code examples
cpointersstructself-reference

Struct Segmentation fault: 11. Unable to reassign values in a struct first initialized to null


I am very new to using a struct so some of the code I am about to show may just be incorrect and that may be the cause of the error I am getting. I am writing code trying to imitate stacks using a struct. I am currently trying to make a pushInt() function that takes in a pointer to a stack struct and some int value. This is the code that I have for the puchInt() function:

    Stack *pushInt(Stack *stack, int value)
    {
        stack->intTop = TRUE;
        stack->data.intValue = value;
        stack->next = NULL;

        return stack;
    } // end pushInt

This is the code that I use to define the stact struct. It is a self referencing struct to act like a likedList:

    struct StackNode
    {
        int intTop;

        union {
            int intValue;
            char stringValue[MAX_STRING_LENGTH];
        } data;

        struct StackNode *next; 
    };

This is the main function that I run to test the functionality of the code:

    int main()
    {
        Stack *theStack = NULL;

        //getInteger function just gets user input
        int pushValue = getInteger("value to push onto stack: ");
        theStack = pushInt(theStack, pushValue);
    }

Solution

  • theStack = pushInt(theStack, pushValue);

    Here the NULL Pointer (theStack initialised with NULL) is passed. So it becomes De-referencing the NULL pointer inside pushInt function and hence the seg fault.

    You need to allocate memory to the variable theStack