我正在用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:Assertion`!cb'失败。
中止(核心转储)
指向结构的指针的地址相同。
需要帮助!
最佳答案
当调用free时,传递的指针指向的内存是
已释放,但调用方中指针的值可能仍保留
不变,因为C的按值传递语义意味着
函数从不永久更改其参数的值。(见
还有问题4.8。)
已释放的指针值严格来说是无效的,
以及对它的任何使用,即使它没有被取消引用(即,即使
使用它是一个看似无害的任务或比较),可以
理论上会导致麻烦。(我们可以假设
实现质量问题,大多数实现不会
为无效的无害使用生成异常的方法
指针,但标准很明确
有保证,并且有这样的系统架构
例外是很自然的。)
当指针变量(或结构中的字段)重复出现时
在程序中分配和释放,设置它们通常是有用的
释放它们后立即空,显式记录它们
国家。
资料来源:
http://c-faq.com/malloc/ptrafterfree.html