Search code examples
cdata-structuresstructstackdynamic-arrays

stackInit function is seg faulting and I'm not understanding why


I'm new to using structures and our current assignment we have to read in a string

for example: "{{asdfd<>}}()()()(((())))"

and for every time we see a "{,[, (, <" we have to push it onto a stack and everytime we see the closing version of the above characters we have to pop the stack. When the array needs to grow, it needs to grow by two.

I know we have to have at least three variables in the structure (element, size of stack, top of stack).

When I run my program in GDB it seg faults in the first "init" function. I've been stuck on this for awhile. Can someone please explain to me what I'm doing wrong.

Thanks!

EDIT: Let me know if there is anything else I need to post. Thanks again!

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

typedef struct dynArrStruct
{
    char *location;
    int length;
    int currSize;
}dynArr;

int checkFlag(int, char**); //checks for the -d flag
void init(struct dynArrStruct*, int);
void push(struct dynArrStruct*, char);
void printAll(struct dynArrStruct*);

int main(int argc, char** argv)
{
    int testFlag, i, size = 0;
    char line[300];
    dynArr* a1;

    printf("Enter a string to be checked: ");
    scanf("%s", line);

    init(a1, strlen(line));

    if(argc > 1)
        testFlag = checkFlag(argc, argv);

    for(i = 0; i < strlen(line); i++)
        if(line[i] == '(' || line[i] == '{' || line[i] == '[' || line[i] == '<')
        {
            size += 2;
            init(a1, size);
            //rest of code here
        }
     // stuff
}

void init(dynArr* a, int size)
{
    a->location = (char *)malloc(sizeof(char) * (size_t)(size));  //SEGFAULT
    a->length = size;
    a->currSize = 0;
}

Solution

  • You don't allocate memory for the dynArr. Either allocate memory on the heap:

    dynArr* a1 = malloc(sizeof(dynArr));
    

    Or allocate it on the stack and use the address-of operator to pass it as a pointer to the init function:

    dynArr a1;
    
    /* ... */
    
    init(&a1, strlen(line));