首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C程序行为怪异

C程序行为怪异
EN

Stack Overflow用户
提问于 2016-01-16 21:48:36
回答 2查看 77关注 0票数 0

我已经开始在C中实现一个循环队列,我有以下代码行:

代码语言:javascript
复制
#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 elementvoid *datastruct element *next字段。怎么能增加一行打印材料,改变程序的行为这么多?

编辑:cirq.h

代码语言:javascript
复制
#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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-16 21:51:28

什么是cirq并不重要,返回本地对象的地址才是问题所在。

这个在这里

代码语言:javascript
复制
cq = &head;

导致未定义的行为,因为这是指针head的地址,该指针仅存储在函数中,当该函数返回时,它将被解除分配,因此无效。在其他地方(函数之外)使用它是未定义的行为。

另外,不要typedef一个指针。永远不要这样做,让代码阅读器知道--它是一个指针

票数 2
EN

Stack Overflow用户

发布于 2016-01-16 21:54:05

这是一种臭味:

代码语言:javascript
复制
if((head = malloc(sizeof(struct element*))) &&

你在调整指针的大小。我想你是想破坏结构本身……?

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34832516

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档