0

This part of the code keeps on giving me segmentation fault. It's a stack structure. For testing I just made a global variable top to keep track of the stack. There's no problem in the logic when I implement it in c++ so I'm not sure why there's an error. Thanks.

struct v
{
  char *value;
  int ibase;
  int obase;
  struct v* next;
};
struct v* top = NULL;

void push(char* val, int ibas, int obas)
{
  struct v* newstackptr;
  newstackptr->next = top;
  newstackptr->value= val;
  newstackptr->ibase= ibas;
  newstackptr->obase= obas;
  top = newstackptr;
}

int main(){
char* value="111";
push(value,2,8);
return 0;
}
akira kato
  • 21
  • 1
  • 5
  • @snr: You need to allocate the memory to hold the `char*` itself too. – ShadowRanger Feb 20 '18 at 19:44
  • you need to strdup(val) too – pm100 Feb 20 '18 at 19:46
  • @ShadowRanger I'm not quite sure if i follow. So i need to allocate memory for char* inside the struct? (char *value=malloc(sizeof(char));) – akira kato Feb 20 '18 at 20:06
  • ...and for the struct itself. You declare a pointer, but it just points to random memory until you give it some. – Lee Daniel Crocker Feb 20 '18 at 20:44
  • @akirakato: I was responding to snr, who (now deleted) claimed the `char*` was fine because what it points to had backing storage, while the `int`s were broken. I was saying that the pointer itself (not what it points to) needed to be allocated, just like the other members of the struct. In any event, his comment was deleted, so it's irrelevant. Point is, at the very least you need to allocate the struct, and in any real code you'd probably want to copy the string (including allocation, e.g. via `strdup`) rather than assuming it will live for the life of the stack. – ShadowRanger Feb 20 '18 at 21:15

1 Answers1

0

You declare newstackptr, but never allocate it, so it has undefined contents, and when you assign its attributes, you're writing to effectively random memory. You need to allocate it:

struct v* newstackptr = malloc(sizeof(*newstackptr));

and you should be increasing the warning level on your compiler in general (e.g. passing -Wall when compiling for gcc/clang), because this sort of error should be trivially identifiable by your compiler.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271