我正在尝试寻找内存泄漏并找到了一个来源。我是一个函数中的指针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)释放记忆,我该如何做才能让匹配仍然包含最好的内容?
我应该做strcpy复制最匹配吗?如果是这样,我是否必须在foo中做另一个malloc?
答案 0 :(得分:1)
在功能栏中,strcpy应显示为
strcpy(*best,s);
在main函数中,您可以通过
复制值最佳点strcpy(match, best);
free(best);
匹配需要指向之前的有效内存块。如果你做了
match = best;
free(best);
匹配也将无效,因为它指向最佳指向的相同释放内存。
答案 1 :(得分:1)
在黑暗中有点刺,假设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;
}
答案 2 :(得分:0)
您需要知道字符串的大小
在(1)您将分配已经释放的内存地址的地址,您必须执行另一个malloc到match*=malloc(sizestr)
,然后如果您想要最好的释放,请使用memmove或strcpy复制它。
如果我理解正确,你想要将字符串复制到最佳,然后自由最好的内存并分配ptr匹配?如果你在memmoving或strcpying到另一个位置之前释放了最好的内存而你丢失了它的内容,如果你想先将它复制到另一个位置,你需要在你要复制它的位置分配内存,所以你需要2个mallocs代码
答案 3 :(得分:0)
如果我必须在(1)而不是(2)释放记忆,我该如何做才能让匹配仍然包含最好的内容?
如果free
位于(1)
位置,则无法执行此操作,以便match
仍然包含best
中包含的内容。
我应该做strcpy复制最佳匹配吗?如果是这样,我是否必须在foo中做另一个malloc?
match = best;
通过上述声明,两者都指向同一位置。因此,根本不需要strcpy
。为此,请为match
分配内存以指定其长度为best+1
,然后执行strcpy
。
答案 4 :(得分:0)
复制指针的值不会复制底层内存。因此,在完成free(best)
之前不要match
,或者您需要malloc
新的缓冲区,例如memcpy()
从一个缓冲区到另一个缓冲区的内容。
答案 5 :(得分:0)
是的,您可以malloc
和strcpy
:
match = malloc(strlen(best) + 1);
strcpy(match, best);
但是,如果您的实现提供了它,您可以使用更容易的strdup()
函数:
match = strdup(best);
如果你还没有strdup(),最好自己创建一个。
答案 6 :(得分:0)
您当前的作业只是将指针指定给同一个缓冲区。如果您然后free()
此缓冲区,则您已删除此处包含的内容(因此取消引用它是一个坏主意)。
您无需使用strcpy()
进行最佳匹配 - 您最好在printf()
之后(或需要的最后一点)释放它。使用额外的函数调用或者六个函数进行过度复杂化是没有意义的,只需记住在每个函数末尾分配的free()
内存!