【问题标题】:confusion about free(pointer) in c关于 c 中的 free(pointer) 的困惑
【发布时间】:2013-07-23 00:59:40
【问题描述】:

我正在尝试使用指针实现堆栈,结构定义在下面的代码中。我为要插入的三个元素(例如:2、4、6)调用了 push() 函数。然后,我调用函数display()。它只显示0。我发现原因是因为我的push() 函数中的free() 函数。但是,我不知道那里到底发生了什么。我不应该使用free() 来释放我的代码中temp 使用的分配内存吗?如果是这样,为什么?

#include<stdio.h>
//#include<unistd.h>
#include<stdlib.h> // malloc ,calloc, free avail here
void push();
void pop();
void display();
struct stack {
    int data;
    struct stack *next;
};

struct stack *start = NULL;

void push()
{
    int ele;
    struct stack *temp, *p;
    printf("entere the element\n");
    scanf("%d", &ele);
    temp = (struct stack *) malloc(sizeof(struct stack));
    temp->data = ele;
    if (start == NULL) {
        start = temp;
        start->next = NULL;
    } else {
        p = start;
        while (p->next != NULL) {
            p = p->next;
        }
        p->next = temp;
        temp->next = NULL;
    }
    free(temp);
}

【问题讨论】:

  • 不要转换malloc()的返回值。
  • @H2CO3 不强制转换 malloc() 的返回值的原因是什么。我想我们应该在这里输入 cast .. 不是吗?
  • @SrinivasThanneeru 我想你错过了void * 隐式兼容(可转换为)任何对象指针类型。事实上,铸造它是一个错误。 Explanation here.
  • @nouney 没错。它还可以隐藏错误。
  • @H2CO3: void* 可隐式转换,但与其他指针类型不“兼容”;该标准对“兼容类型”的定义比隐式可转换性严格得多。转换malloc 的结果通常是个坏主意,但我不会称其为“错误”;我倾向于为需要诊断和/或具有未定义行为的事物保留该词。如果您希望代码编译为 C++,则强制转换甚至是必要的,尽管这并不是一个好主意,几乎像某些人认为的那样频繁。

标签: c pointers memory memory-leaks segmentation-fault


【解决方案1】:
void push(){
               int ele;
               struct stack *temp,*p;
               printf("entere the element\n");
               scanf("%d",&ele);
               temp=(struct stack *)malloc(sizeof(struct stack ));
               temp->data=ele;
               if(start==NULL){
               start=temp;
               start->next=NULL;
            }
           else{
                p=start;
                while(p->next !=NULL){
                                       p=p->next;
                 }
                p->next=temp;
               temp->next=NULL;
            } 
            free(temp); // don't free temp here !  
          }

只有在不再需要指针时才需要释放它。您可能会认为是这样,因为您不使用temp,但事实并非如此。 free 的参数是一个有效的内存地址。 temp 是一个有效的内存地址,但您将 temp 分配给 start !所以:free(tmp)free(start) 相同,这不是你想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 2014-11-29
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多