我正在执行一段代码,尝试使用动态数组。这行出现段错误:
void myFunction(....) {
// other code up here
Stack *s = stack_new(); //segfault here
}
我的结构的相关头文件是:
typedef struct {
void **A;
int size;
int top; // the index of the current top of the stack
} Stack;
函数 stack_new() 是:
Stack
*stack_new() {
Stack *s;
s->size = 1;
s->top = -1;
s->A = (void **)malloc(s->size);
return s;
}
我想我已经包含了所有相关的内容,但如果您需要更多代码,请告诉我。
我认为问题出在我使用 malloc 的方式上,但在网上进行了搜索并尝试了一些不同的选项,但仍然遇到段错误。有谁可以提供一些见解吗?
这是你的问题:
Stack *s;
s->size = 1;
您实际上并未分配
Stack
。 s
未初始化,指向内存中的任意位置。 s->size
显然会失败。
尝试:
Stack *s = malloc(sizeof(*s));
if (s == NULL)
{
fprintf(stderr, "Memory allocation error\n");
exit(1);
}
s->size = 1;
注意:您还应该检查
s->A
是否为 NULL
。如果是这样,请返回错误代码(例如 NULL
),在此之前请记住释放您分配的 Stack
,或者打印错误消息并退出程序。如果退出程序,操作系统将回收所有使用的内存,因此无需显式执行此操作。
另一个注意事项:做的时候
s->size = 1;
s->top = -1;
s->A = (void **)malloc(s->size);
...即使您应该分配
sizeof(void*)
字节内存,您也分配了 1 字节内存。尝试做一下
s->A = (void **)malloc(s->size*sizeof(void*));
相反。
这是你的第一个问题:
Stack *s;
s->size = 1;
此时您实际期望
s
的值是多少?它可能是字面上的任何东西。如果结构本身尚未分配,则无法设置结构的字段。
尝试:
Stack *s = malloc(sizeof(*s));
if(!s){
//... error checking / exiting ..
}
然后是你正在做的所有其他事情。
您正在访问一个未初始化的指针!
Stack
*stack_new() {
Stack *s = std::nullptr; // initialize this pointer with nullptr
// and then you will see later (one line
// beyond) that you will try to access a
// null pointer
s->size = 1; // the problem occurs here!!
// you are accessing a pointer, for which has never
// been allocated any memory
s->top = -1;
s->A = (void **)malloc(s->size);
return s;
}
您必须使用“malloc”为此指针分配一些内存。 某事。就像这两行之间缺少这个一样,我评论道:
堆叠
*stack_new() {
Stack *s = (Stack*)malloc(sizeof(Stack));
s->size = 1;
s->top = -1;
s->A = (void **)malloc(s->size);
return s;
}