我正试图追查内存泄漏并找到了一个来源。我在一个函数中 malloc'in 指针并在另一个函数中释放它,但我错过了理解如何复制指针指向的值同时也能够释放指针。
Current implementation (with memory leak):
// This code has been greatly simplified
// and as such does not appear to have any purpose
int foo(){
int bestval = 0;
char *best;
char *match;
for (int i=0;i<3;i++) {
int returnValue = bar(&best);
if (returnValue > 10) {
(1)
match = best;
}
}
printf("%s", match);
(2)
return 0;
}
int bar(char ** best) {
char*s = "Hello!";
*best = malloc(strlen(s) + 1);
strcpy(*best,s);
return 0;
}
两个问题
如果我必须在 (1) 而不是 (2) 处释放内存,我该怎么做才能使匹配项仍然包含 best 中包含的内容?
我应该执行 strcpy 以复制最佳匹配吗?如果是这样,我是否必须在 foo 中执行另一个 malloc?
最佳答案
假设在 Foo 中有一个循环...有点摸不着头脑......
int foo()
{
int bestval = 0;
char *best;
char *match = 0; // initialize to null
// start some loop
for (int i=0;i<3;i++) {
// fetch the next best value...
int returnValue = bar(&best);
// some check (if best is really best!)
if (returnValue > 10) {
// if match has previously been populated, free it
if(match) {
free(match);
}
// save the new best value
match = best;
}
else {
// not saving best in match, so free it!
free(best);
}
}
// end some loop
// only do this if match was successful?!?
if(match) {
printf("%s", match);
// clean up once the best of the best has been used...
free(match);
}
return 0;
}
关于复制和释放 malloc 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5618006/