如本主题的主题所示。我有一个简单的功能:
char *to_str(int x)
{
char *s = malloc(6);
if (s == NULL) {
error("malloc");
}
snprintf(s, sizeof(s), "%d", x);
return s;
}
在它的主体中分配内存,并返回这样的值。我应该如何处理内存释放?什么是最好的方法?
最佳答案
How should I handle memory deallocation?
小心。绝对比你现在做得更好。
What would be the best approach?
最好的方法是在您不再需要时free()
内存:
char *str = to_str(1337);
// do stuff with `str'
free(str);
此外,sizeof()
是错误的。它为您提供指针的大小,而不是缓冲区的大小。您需要自己跟踪它。
关于c - 如何释放函数中分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16131155/