【问题标题】:EXC_BAD_ACCESS in stack implementaton堆栈实现中的 EXC_BAD_ACCESS
【发布时间】:2014-09-19 23:07:16
【问题描述】:

我正在尝试编写一个程序来检查平衡括号,但是当我尝试初始化堆栈/数组时,我得到了错误的访问(代码=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;

我无法弄清楚为什么它给了我一个错误的访问权限,任何帮助/建议将不胜感激!

先谢谢你了。

【问题讨论】:

  • stack-&gt;content : stack 为 NULL。
  • @BLUEPIXY stack 未初始化
  • @AlexD 未经证实。
  • 我正在尝试使用 Init 对其进行初始化,并使用 Stack *stack 声明它。 Init 函数正在初始化它,或者至少我认为。
  • @PM 试试Stack stack;Init(&amp;stack);Stack *stack=malloc(sizeof(*stack));Init(stack);

标签: c xcode xcode5 exc-bad-access


【解决方案1】:

你已经定义了一个栈指针,它不会分配内存。

在调用 Init 之前,您需要在 CheckBalancedParentheses 中有一个 malloc 语句:

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

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 2019-11-11
    • 2010-11-27
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多