免费指针传递给C中的另一个功能
我想在另一个函数中释放指针以将行保存在我的实际功能中,但是当我使用此自编写功能时:
void free_func(char *ptr1, char *ptr2)
{
if (ptr1)
{
free(ptr1);
ptr1 = NULL;
}
if (ptr2)
{
free(ptr2);
ptr2 = NULL;
}
}
它不能释放我的指针。 这是我称之为free_function的主要功能:
int main(void)
{
char *test;
test = (char *)calloc(5, sizeof(char));
test[0] = 'h';
test[1] = 'e';
test[2] = 'y';
test[3] = '\0';
printf("test before: %s\n", test);
//free_func(test, 0, 0);
free(test);
test = NULL;
printf("test after: %s\n", test);
return(0);
}
这将为我提供预期的输出:
test before: hey
test after: (null)
但是,如果我评论了我的释放的行并使用null,并且我的free_func不注重我,我将获得此输出:
test before: hey
test after: hey
我现在的问题:为什么我自写的免费功能会做一些不同的事情,然后是我的主要功能中的实际相同行?
I want to free a pointer in another function to save lines in my actual function, but when i use this self-written function:
void free_func(char *ptr1, char *ptr2)
{
if (ptr1)
{
free(ptr1);
ptr1 = NULL;
}
if (ptr2)
{
free(ptr2);
ptr2 = NULL;
}
}
it doesn't free my pointer.
This is my main function where i call my free_function:
int main(void)
{
char *test;
test = (char *)calloc(5, sizeof(char));
test[0] = 'h';
test[1] = 'e';
test[2] = 'y';
test[3] = '\0';
printf("test before: %s\n", test);
//free_func(test, 0, 0);
free(test);
test = NULL;
printf("test after: %s\n", test);
return(0);
}
This will give me the expected output:
test before: hey
test after: (null)
But if i comment the line where i free and use NULL, and uncomment my free_func, i will get this output:
test before: hey
test after: hey
My question now: why does my self written free function does something different, then the actual same lines in my main function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你错了。它确实可以释放您的指针指向的内存(即返回的内存为
calloc
)。没有办法检查一下。好吧,除了使用
-fsanitize =地址
或valgrind
之类的东西以检查内存泄漏。实际上,他们做同样的事情。他们释放内存,然后将变量设置为
null
。唯一的区别是您打印的变量(
test
)不是您在使用该函数时设置为null
(ptr1
)的变量。如果您希望该函数更改呼叫者中的变量,则需要将其授予地址为变量。至少,这是正常的解决方案。在这里它不太有用,因为我们想接受任何指针。在X86/X86-64上,所有指针的尺寸都是相同的,并且每种指针的null都是相同的。但到处都不是这样。因此,上述法规违反了标准和警告。
在这里,可以使用宏。
You are mistaken. It does free the memory to which your pointer points (i.e. the memory returned be
calloc
).There's no way to check this. Well, short of using something like
-fsanitize=address
orvalgrind
to check for memory leaks.Actually, they do exactly the same thing. They free the memory, then set the variable to
NULL
.The only difference is that the variable you print (
test
) isn't the variable you set toNULL
(ptr1
) when using the function. If you want the function to change the variable in the caller, you will need to give it the address the variable.At least, that's the normal solution. It doesn't quite work here since we want to accept any kind of pointer. On a x86/x86-64, all pointers are the same size, and NULL is the same for every type of pointer. But that's not the case everywhere. As such, the above code violates the standard and warns.
Here, a macro could be used.