gpt4 book ai didi

c - 使用语言 c 时在 .h 和 .c 中 malloc 和 free

转载 作者:太空宇宙 更新时间:2023-11-04 05:37:36 25 4
gpt4 key购买 nike

我是 C 编程的新手,我对 malloc() 感到很困惑和 free() .

我需要从文件 (.yaml) 中读取一些随机数的随机数据值并将它们存储在 hashmap 中,类似于 < char *key_name, char *type, void *value > .

我正在使用 void *存储任何类型数据的指针,我读为 char * ,所以我想编写自己的函数来确定数据类型并返回大小合适的指针以将其传递给进一步的任务。

我希望这个函数在我的小解析器(myparser.h 和 myparser.c)中,以便将来将其用作库。

但是!例如,我在 myparser.c 中为读取的每个浮点值执行了这段代码:

void *parser_get_pointer(char *token_value, char *type) {
...
else if (strcmp(type, "float") == 0) {
printf("Type float recognized\n");

float *fp = (float *)malloc(sizeof(float));
*fp = atof(token_value);

void *result = (float *)malloc(sizeof(float));
result = fp;


return (float *)result;
}
...
}

主要问题是我应该在哪里做free(fp)所以我不会丢失 main.c 中的数据?

最佳答案

关于malloc()calloc() 的一些普遍接受的想法 realloc() 函数使用:

1) 在使用 C 时不要转换这些函数的返回值。

int *a = (int)malloc(10*sizeof(int)); //wrong
int *a = malloc(10*sizeof(int)); //correct

2)检查函数的返回值

int *a = malloc(10*sizeof(int));
a[0] = 10; //wrong - if malloc failed, a will be NULL.

int *a = malloc(10*sizeof(int));
if(a)
{
a[0] = 10; //correct

3) 在 realloc() 的情况下使用 tmp 变量来避免内存泄漏

tmp = realloc(orig, newsize);
if (tmp == NULL)
{
// could not realloc, but orig still valid
}
else
{
orig = tmp;
}

4) 每次调用 [c][m][re]alloc()

int *a = malloc(10*sizeof(int));
if(a)
{
a[0] = 10; //correct
...
free(a);
}
else
{
//handle error
}

不这样做导致内存泄漏。

关于c - 使用语言 c 时在 .h 和 .c 中 malloc 和 free,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28989205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com