malloc的奇怪行为

alv*_*zoo 1 c linux malloc struct system

我正在尝试动态初始化队列.这是我的功能.

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);
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

注意有两个dump_queue,一个是init_queue(),另一个是init_queue之后.由于task_queue是malloced,我希望dump_queue的两次调用应该给出相同的结果.但第二个实际上报告了一个SIG_FAULT.

在我检查之后,在dump_queue的第二次调用中,task_queue实际上是NULL.这是为什么?

Nat*_*tta 5

为什么不?你的内存分配函数的局部范围init_queue().

返回指针的范围有效,但赋值无效.

q = malloc(sizeof(queue));
Run Code Online (Sandbox Code Playgroud)

q不会保留它在init_queue()功能之外的价值.

如果queue * task_queue;是全局的,是否真的需要将其作为函数参数传递?

另外,作为注释,请不要转换返回值malloc().


编辑:

不,没有auto-free()概念c.如果没有显式的应用程序-d ,它将导致内存泄漏free().