我已经开始在C中实现一个循环队列,我有以下代码行:
#include <stdio.h>
#include <stdlib.h>
#include "cirq.h"
//allocate a circular queue
cirq cq_alloc(void){
cirq cq = NULL;
element *head;
element *tail;
if((head = malloc(sizeof(struct element*))) &&
(tail = malloc(sizeof(struct element *)))){
head->content = 0; // head node keeps track of size.
tail->content = NULL;
head->next = tail;
tail->next = head;
cq = &head;
} else {
printf("ERROR: No space for more cqueues.\n");
}
return cq;
}
int cq_size(cirq q){
return (int)(*q)->content;
}
int main(){
cirq q = cq_alloc();
printf("Size of element ptr %lu\n", sizeof(struct element *));
printf("%d\n", cq_size(q));
return 0;
}现在,当我编译和运行这个程序时,在main中注释掉了打印出sizeof(struct element *))的行后,程序运行良好,队列大小为0。当我离开行的时候,struct的大小会被打印出来,但在那之后我得到了一个segmentation fault: 11。另外,为了说明问题,struct element有void *data和struct element *next字段。怎么能增加一行打印材料,改变程序的行为这么多?
编辑:cirq.h
#ifndef CIRQ_H
#define CIRQ_H
typedef struct element **cirq; // cirq handle
typedef struct element {
void *content;
struct element *next;
} element;
extern cirq cq_alloc(void);// allocate a queue
extern int cq_size(cirq q);// return the size of a queue
extern void cq_enq(cirq q, void *value);// add a value to the queue
extern void *cq_deq(cirq q);// dequeue and return a queue value
extern void *cq_peek(cirq q);// return the value at the queue head
extern void cq_rot(cirq q);// requeue the head element at the tail
extern void cq_free(cirq q);// return all space allocated to queue
#endif发布于 2016-01-16 21:51:28
什么是cirq并不重要,返回本地对象的地址才是问题所在。
这个在这里
cq = &head;导致未定义的行为,因为这是指针head的地址,该指针仅存储在函数中,当该函数返回时,它将被解除分配,因此无效。在其他地方(函数之外)使用它是未定义的行为。
另外,不要typedef一个指针。永远不要这样做,让代码阅读器知道--它是一个指针。
发布于 2016-01-16 21:54:05
这是一种臭味:
if((head = malloc(sizeof(struct element*))) &&你在调整指针的大小。我想你是想破坏结构本身……?
https://stackoverflow.com/questions/34832516
复制相似问题