Home > Net >  Segmentation fault (Core Dump) while creating stack using pointer
Segmentation fault (Core Dump) while creating stack using pointer

Time:11-04

Could you please help me to find out why I'm getting the segmentation fault (Core Dumped) error?

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

struct stack {
    int size;
    int top;
    int *arr;
};

int main(){
struct stack *ptr;
ptr->size = 10; //Code is not going ahead after this line(Segmentation fault)
ptr->top = -1;
ptr->arr = (int *)malloc(ptr->size * sizeof(int));

return 0;
}

Trying to create a stack using pointers but while I run this code I m getting this error and I m not able to go ahead without solving this error. Wants to know what is the reason behind it. I read all the reasons for the segmentation error but was not able to solve the error.

CodePudding user response:

You are getting segmentation fault because you have no ptr allocated.

ptr is struct stack*, a pointer.

And it was not even initialized.

from your code

    struct stack* ptr;
    ptr->size = 10;

But ptr points to what?

A safe way:

#include<stdlib.h>

typedef struct st_stack
{
    int  size;
    int  top;
    int* arr;
} Stack;

int main(void)
{
    Stack* ptr = (Stack*)malloc(sizeof(Stack));
    ptr->size = 10;
    ptr->top  = -1;
    ptr->arr  = (int*)malloc(ptr->size * sizeof(int));

    free(ptr->arr); // free array
    free(ptr); // free stack

    return 0;
}

Note to code police: I always cast the return of malloc(). Yes, I know about the C-FAQ from the 90's (never updated). I do this because, as many others, I do no like implicit conversions. For the compiler void* is ok. The cast is a reminder for the programmer of what is being allocated at each call, and helps to avoid many bugs. malloc() accepts any expression that evaluates to a size_t and in many cases it is hard to know, in a series of allocations, which is which.

C-FAQ list a big advantage of not using a cast: the compiler will alert you if you forget to #include stdlib.h. Well, if someone needs this kind of reminder there are bigger problems to solve. ;)

  • Related