0

I have these two structs

struct node{
    int val;
    struct node *up;
    struct node *down;
};

struct stack {
    struct node *bottom;
};

The typedef struct is defined in a header file

typedef struct stack stack_set;

I am trying to malloc the structs but I keep getting seg faults when I try to access the node struct. I have tried using malloc on the node struct to no avail.

    stack_set *set;
    set = malloc(sizeof(stack_set));
    set->bottom = NULL;
    set = malloc(sizeof(struct node));
    set->bottom->val = NULL;
    return set;

I hit a seg fault on the second last line of code.

How do I properly malloc my code so I don't keep throwing seg faults? I haven't been able to find an example that could aid in resolving mine.

Thanks

2 Answers 2

3

It looks like misptint in fourth line (also you mix root and bottom). Try this:

stack_set *set;
set = malloc(sizeof(stack_set));
set->bottom = malloc(sizeof(struct node));
set->bottom->val = 0;     // it is better to initialize
set->bottom->up = NULL;   // all fields to avoid undefined
set->bottom->down = NULL; // behaviour in the future
return set;

Also it is better to check result of memory allocation functions:

stack_set *set;
set = malloc(sizeof(stack_set));
if (!set)
  return NULL;
set->bottom = malloc(sizeof(struct node));
if (!set->bottom) {
  free(set);
  return NULL;
}
set->bottom->val = 0;
set->bottom->up = NULL;
set->bottom->down = NULL;
return set;
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thankyou, it works now :D I'll definitely utilise this thorough checking method as well. Cheers!
3

The standard malloc(3) function. is returning uninitialized memory. You need to initialize it. So after

    set = malloc(sizeof(struct node));

all of your set fields contain garbage values (or malloc failed and gave NULL). In particular you should not dereference set->root, this is undefined behavior, and might seems to work if unlucky.

I would recommend using callocto get zeroed memory:

   set = calloc(1, sizeof(struct stack));
   if (!set) {perror("calloc stack"); exit(EXIT_FAILURE); };
   set->bottom = calloc(1, sizeof(struct node));
   if (!set->bottom) {perror("calloc node"); exit(EXIT_FAILURE); };

If you can't use calloc clear the memory using memset.

Compile with all warnings and debug info (gcc -Wall -g) and use valgrind if available.

1 Comment

Thankyou for the answer and the tips on using calloc. I will try use valgrind as well.

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.