Segfault using dynamic array

I'm executing a piece of code where I'm trying to use a dynamic array. It is segfault-ing at this line:

void myFunction(....) {
     // other code up here
     Stack *s = stack_new(); //segfault here

The relevant header file for my struct is:

typedef struct {
    void **A;   
    int size;   
    int top;    // the index of the current top of the stack
} Stack;

and the function stack_new() is:

*stack_new() {
    Stack *s; 
    s->size = 1; 
    s->top = -1; 
    s->A = (void **)malloc(s->size);
    return s;

I think I've included everything that is relevant, but please let me know if you need more code.

I think that the problem is with the way I'm using malloc, but have had a search online and have tried a few different options and am still getting the segfault. Is anyone able to offer some insight?


  • This is your problem:

    Stack *s; 
    s->size = 1;

    you're not actually allocating a Stack. s is uninitialized and points to an arbitrary location in the memory. s->size will obviously fail then.


    Stack *s = malloc(sizeof(*s));
    if (s == NULL)
        fprintf(stderr, "Memory allocation error\n");
    s->size = 1;

    Note: you should also check if s->A is NULL. If so, return an error code (such as NULL) and before that remember to free the Stack you allocated, or alternatively print an error message and exit the program. If you exit the program, the operating system will reclaim all memory used so no need to do it explicitly then.

    Another note: when doing

    s->size = 1; 
    s->top = -1; 
    s->A = (void **)malloc(s->size);
 allocate 1 byte of memory even though you should be allocating sizeof(void*) bytes of memory. Try doing

    s->A = (void **)malloc(s->size*sizeof(void*));