我正在尝试动态初始化队列。这是我的功能。
typedef struct{
int size;
int max_size;
short * eles;
} queue;
void dump_queue(queue *q)
{
//print a bunch of information
}
void init_queue(queue *q, int max_size)
{
q = (queue)malloc(sizeof(queue));
q->size = 0;
q->max_size = max_size;
q->eles = (short *)malloc(max_size * sizeof(short));
int i;
for(i = 0; i < max_size; i++)
q->eles[i] = -1;
dump_queue(q);
}
task_queue 是一个全局变量。例程的结构如下:(不是确切的代码)
//globally defined here but not initialized
queue * task_queue;
void init_scheduler()
{
init_queue(task_queue, 32);
dump_queue(task_queue);
//other staff
}
注意dump_queue有两个,一个是init_queue(),一个在init_queue之后。由于 task_queue 是 malloced,我希望 dump_queue 的两次调用应该给出相同的结果。但是第二个实际上报告了一个 SIG_FAULT。
我查了一下,在第二次调用dump_queue的时候,task_queue其实是NULL。这是为什么?
最佳答案
为什么不呢?您正在 init_queue()
的函数局部作用域中分配内存。
返回指针的范围有效,但赋值无效。
q = malloc(sizeof(queue));
这个 q
不会在 init_queue()
函数之外保持它的值。
如果 queue * task_queue;
是全局的,是否真的需要将它作为函数参数传递?
另请注意,请do not cast malloc()
的返回值。
编辑:
不,c
中没有auto-free()
概念。它将导致内存泄漏,如果不是 free()
-d 由应用程序显式控制。
关于c - malloc 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27268947/