我正在重新学习 C,并使用splint
它来测试我的源代码。
我正在尝试执行以下操作:
- 创建具有“构造函数”功能的结构
- 使用“析构函数”销毁结构,释放结构的内存。
但是,当我使用夹板测试我的代码时,它会发出与析构函数中的临时存储相关的警告,以及调用析构函数后的内存泄漏。
我想知道(a)夹板对于我的代码中的内存泄漏是否正确(我认为不是),以及(b)我应该做什么来修复我的代码或让夹板了解我在做什么。
无论如何,这是代码:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
// define the structure
struct Boring {
int amount;
};
// the creator
static struct Boring *Boring_create(int amount) {
struct Boring *really = malloc(sizeof(struct Boring));
assert(really != NULL);
really->amount=amount;
return really;
}
// the destroyer
static void Boring_destroy(struct Boring *really) {
assert( really != NULL );
// free the memory of the Boring structure
free(really);
}
int main( /*@unused@*/ int argc, /*@unused@*/ char *argv[]) {
int amount = 5;
struct Boring *tv = Boring_create(amount);
printf("The TV is boring level %d\n",tv->amount);
// destroy the tv!
Boring_destroy(tv);
printf("The TV is now boring level %d\n",tv->amount);
return 0;
}
/* Output */
/*
* $> ./destroytv
* The TV is boring level 5
* The TV is now boring level -538976289 (or 0 depending on OS/compiler)
*/
代码使用 gcc 编译并运行良好。
但是,当我使用夹板对其进行测试时,夹板会发出以下警告:
$> splint boringtv.c
destroytv.c: (in function Boring_destroy)
destroytv.c: Implicitly temp storage really passed as only param: free (really)
Temp storage (associated with a formal parameter) is transferred to a new non-temporary reference. The storage may be released or new aliases crated. (Use -temptrans to inhibit warning)
destroytv.c: (in function main)
destroytv.c: Fresh storage tv not released before return
A memory leak has been detcted. Storage allocated locally is not released before the last reference to it is lost (use -mustfreefresh to inhibit warning)
Fresh storage tv created
第一次警告,越想越不明白。但是我还没有阅读足够多的手册来证明关于该手册的正确问题。
第二个警告,关于内存泄漏,似乎夹板只是没有意识到内存在其他地方被释放,这对我来说似乎很奇怪。free()
如果我只是在里面打电话,警告就会消失main
。
在此先感谢您的帮助。请让我知道是否有更多详细信息(例如警告的行号)会有所帮助。