简体   繁体   English

stackInit函数出现段错误,我不明白为什么

[英]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<>}}()()()(((())))" 例如:“ {{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. 当我在GDB中运行程序时,它会在第一个“ init”函数中出现段错误。 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;
}

You don't allocate memory for the dynArr . 您没有为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: 或在堆栈上分配它,并使用address-of运算符将其作为指向init函数的指针传递:

dynArr a1;

/* ... */

init(&a1, strlen(line));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM