gpt4 book ai didi

c - 堆栈实现中的 EXC_BAD_ACCESS

转载 作者:行者123 更新时间:2023-11-30 15:29:58 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来检查括号是否平衡,但是当我尝试初始化堆栈/数组时,我遇到了错误的访问(代码=1,地址0x0)。

这是代码:

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

#define TRUE 1
#define FALSE 0

#define MAX_STRING_LEN 1000
#define MAX_STACK_SIZE 5000

typedef char StackElement;

typedef struct Stack{
StackElement *content;
int maxSize;
int top;
}Stack;


void Init(Stack*stack);
void Destroy(Stack*stack);
void Push(Stack*stack, StackElement element);
StackElement Pop(Stack*stack);
int IsEmpty(Stack*stack);
int IsFull(Stack*stack);



/*
* A new stack variable is initialized. The initialized
* stack is made empty. MaxSize is used to determine the
* maximum number of character that can be held in the
* stack.
*/
void Init(Stack *stack)
{
StackElement *newContent;

/* Allocate a new array to hold the content.*/
newContent = (StackElement*)malloc(sizeof(StackElement)* MAX_STACK_SIZE);

if (newContent == NULL) {
printf("Insufficient memory to initialize stack.\n");
exit(1);/* Exit, returning error code.*/
}

stack->content = newContent;
stack->maxSize = MAX_STACK_SIZE;
stack->top = -1;
}

int CheckBalancedParentheses (char* expression){
int i = 0;
Stack *stack;
Init(stack);

if (strcmp(&expression[i], ")") == 0 || strcmp(&expression[i], "]") == 0 || strcmp(&expression[i], "}") == 0){
return FALSE;
}

for (i = 0; i < strlen(expression); i++){
if (strcmp(&expression[i], "(") == 0 || strcmp(&expression[i], "[") == 0 || strcmp(&expression[i], "{") == 0){
Push(stack, expression[i]);
}
}

return TRUE;
}

所有这些线路上都发生了错误的访问(我单独测试了它们):

stack->content = newContent;
stack->maxSize = MAX_STACK_SIZE;
stack->top = -1;

我不明白为什么它给我带来了不好的访问,任何帮助/建议将不胜感激!

提前谢谢您。

最佳答案

您已经定义了一个堆栈指针,这不会分配内存。

在调用 Init 之前,您需要在 CheckBalancedParentheses 中添加 malloc 语句:

/* Allocate memory for our stack */
Stack* stack = malloc( sizeOf(Stack) );

关于c - 堆栈实现中的 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25943574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com