【发布时间】:2014-02-08 16:53:10
【问题描述】:
我正在尝试掌握 c 的窍门,但我不知道为什么这段代码会产生段错误。
// In src/test.c
#include <stdio.h>
typedef struct {
int length;
int *arr[1000];
} Stack;
void push(Stack *stack, int el) {
(*stack->arr)[stack->length++] = el;
}
int pop(Stack *stack) {
return (*stack->arr)[--stack->length];
}
int main(int argc, char* argv[]) {
Stack stack;
push(&stack, 5);
printf("%d\n", pop(&stack));
return 0;
}
然后我编译运行:
$ gcc src/test.c -o test && ./test
[1] 79484 segmentation fault ./test
【问题讨论】:
-
好吧,是哪一行导致了错误???
-
我什至不知道如何找到,但在缩小代码范围后,我相当确定它在
push或pop函数中。对 c 来说仍然非常新。 -
你没有初始化
stack.length。 (并使用-g编译并使用gdb进行调试。) -
int *arr[1000]真的是你想要的吗? -
另外,您将指针数组与指向数组的指针混淆了,并且您没有为指针分配内存。
标签: c memory segmentation-fault