【发布时间】: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 谢谢。但如果是这样,我怎么能有证据证明免费功能有效?