1

How does my code actually give a segmentation fault?

I'd like to keep TOS as a double pointer.

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

typedef struct node_tag{
    int num;
    struct node_tag* next;
}NODE;

void push(int x, NODE **TOS){
    NODE* temp = (NODE*) malloc(sizeof(NODE));
    temp->num = x;
    temp->next = (*TOS);
    (*TOS) = temp;
}

int main(){
    NODE **TOS = NULL, *temp;
    printf("<<<Stack Push>>>\n");
    push(0, TOS);
    printf("%i\n", (*TOS)->num);
}
Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
Jsandesu
  • 105
  • 12
  • 2
    cause you're dereferencing `NULL` in this code. –  May 01 '18 at 16:38
  • 2
    `NODE **TOS = NULL` -> `NODE *TOS = NULL`, `push(0, TOS);` -> `push(0, &TOS);`, `printf("%i\n", (*TOS)->num);` -> `printf("%i\n", TOS->num);` –  May 01 '18 at 16:39
  • `malloc` returns a `void` pointer which is automagically converted to any other type. Do not cast the return value from `malloc`, doing so can mask coding errors that the compiler might have detected for you. – jwdonahue May 01 '18 at 17:17
  • @BakaBaka if your question was solved you can mark this question as resolved by clicking the check mark next to the answer you found most useful. – Increasingly Idiotic May 17 '18 at 20:27

1 Answers1

1

You need to use it like this;

int main(){
    NODE *TOS = NULL, *temp;
    printf("<<<Stack Push>>>\n");
    push(0, &TOS);
    printf("%i\n", TOS->num);
}
cleblanc
  • 3,678
  • 1
  • 13
  • 16