[英]malloc inside function causing SIGSEV
I am trying to write a generic queue implementation in C. For the initialization part, this is what I have: 我正在尝试用C语言编写一个通用队列实现。对于初始化部分,这就是我所拥有的:
struct queue{
int head;
int tail;
int max_size;
int elem_size;
void **elements;
};
void queue_init(struct queue** q, int max_size, int elem_size){
*q = malloc(sizeof(struct queue));
(*q)->head = (*q)->tail =0;
(*q)->max_size = max_size;
(*q)->elem_size = elem_size;
(*q)->elements = malloc(max_size * elem_size);
}
To test the implementation, I wrote the following: 为了测试实现,我编写了以下内容:
void klein_test(void){
struct queue** qp;
queue_init(qp, 1, 1);
return;
}
int main(){
klein_test();
}
While trying to run such test, I got a SIGSEV
. 在尝试进行此类测试时,我得到了
SIGSEV
。 Inspecting the execution with gdb
, I could see that the error signal was being generated at queue_init
's first call to malloc
. 通过
gdb
检查执行情况,我可以看到在queue_init
首次调用malloc
生成了错误信号。 What is the cause of such behaviour? 这种行为的原因是什么?
At least write 至少写
struct queue* qp;
queue_init(&qp, 1, 1);
Also it is not clear why there is declaration 也不清楚为什么有宣言
void **elements;
instead of just 而不只是
void *elements;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.