【问题标题】:C: free memory allocated to a struct doesn't workC:分配给结构的空闲内存不起作用
【发布时间】:2016-03-21 12:56:47
【问题描述】:

我正在用 C 编写一个环形缓冲区。 我最终被困在释放内存上。 代码编译良好,但结果显示circBuf_free 函数未能释放分配的内存。 相关代码为:

#include <stdint.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //memcpy

#define kNumPointsInMyBuffer 16 
#define initialSize 10


typedef struct CircBuf_t //struct name CircBuf_t
{
    uint32_t *buffer;
    int head; // keep track the newest data
    int tail; // keep track the oldest data
    int maxLen; // maximum number of items in the buffer
}circBuf_t; //type name circBuf_t


 // initialize the circular buffer
void circBuf_init(circBuf_t *c, const int maxLen, int sz)
{
    c->buffer = malloc(maxLen * sz);
    c->maxLen = maxLen;
    if(c->buffer == NULL)
    printf("Buffer initialization fails\n");
    c->head = 0;
    c->tail = 0;
}

/* free the memory, free c->buffer first, then c*/
void circBuf_free(circBuf_t *c){
    free(c->buffer);
    free(c);
}


int main(){
// initilize ring Buffer    
const int maxLen = kNumPointsInMyBuffer;

// original src
int src[1024] = {};
int i =0;
for(i=0; i<1024; i++){
    src[i] = i;
}

//data
uint32_t data[1024];    
memcpy(data, src, 1024);

printf("\nThe size of the uint32_t data array is %lu\n", sizeof(data));
int sz = sizeof(*data);

circBuf_t *cb;
cb = malloc(sizeof(circBuf_t));
circBuf_init(cb, maxLen, sz);



assert(cb);
printf("cb's value is %p\n", cb);
circBuf_free(cb);
printf("cb's value is %p\n", cb);
assert(!cb);

return 0;
}

结果:

cb的值为0x1266010

cb的值为0x1266010

a.out: sample.c:73: main: 断言 `!cb' 失败。

中止(核心转储)

指向结构的指针的地址是一样的。

需要帮助!

【问题讨论】:

  • 预计是一样的。释放内存只会释放内存,不会修改任何变量。
  • @molbdnilo 谢谢。但如果是这样,我怎么能有证据证明免费功能有效?

标签: c pointers struct free


【解决方案1】:

调用free时,传递的指针指向的内存是 已释放,但调用者中指针的值可能仍然存在 不变,因为 C 的按值传递语义意味着调用 函数永远不会永久更改其参数的值。 (看 还有问题 4.8。)

一个被释放的指针值,严格来说是无效的, 以及对它的任何使用,即使它没有被取消引用(即,即使 使用它是一个看似无害的分配或比较),可以 理论上会导致麻烦。 (我们大概可以假设,作为 实施质量问题,大多数实施不会退出 他们如何为无效的无害使用生成异常 指针,但标准明确表示没有什么是 保证,并且有这样的系统架构 例外是很自然的。)

当指针变量(或结构中的字段)重复出现时 在程序中分配和释放,设置它们通常很有用 释放它们后立即为 NULL,以显式记录它们 状态。

来源: http://c-faq.com/malloc/ptrafterfree.html

【讨论】:

  • 非常感谢!所以指针的值不变,但是内存已经被释放了。这只是让我不放心。
猜你喜欢
  • 2017-06-06
  • 2015-03-21
  • 2014-11-27
  • 2011-07-13
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
相关资源
最近更新 更多