c - malloc 的奇怪行为

标签 c linux struct malloc 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);
}

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/

相关文章:

linux - 仅当尚未添加值时才使用 bash 将值添加到数组

arrays - 为什么不能超过 *[]Struct?

C++:如何洗牌动态指针数组?

c - 循环时间调度中的时间片

c - `int` 类型大小 int C

c - C中的fwide函数是什么

python - python中的列表索引超出范围

c++ - 如何为 llvm IR 调用指令创建结构参数?

c - l 值的 c 的奇怪语法(在 linux 内核 : per_cpu)

javascript - C/SSL/JQuery.ajax() 客户端 -> 服务器连接重置,但发送了 1 个字节