而错误使用C释放内存 [英] Error while freeing memory in C
问题描述
我已经写练习指针和分配内存的一个问题。
不过,我得到一个堆栈转储,当我释放内存。我在正确的位置释放?还有什么毛病我的程序,可以使它不安全?
无效display_names(字符** names_to_display,焦炭**输出);INT主要(无效)
{
字符*名称[] = {路加福音,约翰,彼得,0};
焦炭** my_names =名称;
字符* new_output [1024] = {0};
为size_t I = 0; //打印序号名称
而(* my_names)
{
的printf(名称:%s \\ n,* my_names ++);
} my_names =名称; /* 重启 */
display_names(my_names,new_output); //打印更新的名称
而(new_output [I])
{
的printf(全名:%S \\ n,new_output [I]);
我++;
} //自由分配的内存
免费(new_output); 的getchar(); 返回0;
}无效display_names(字符** names_to_display,焦炭**输出)
{
而(* names_to_display)
{
*输出=(字符*)malloc的(strlen的(全名)+ strlen的(* names_to_display)+ 1);
如果(!*输出)
{
fprintf中(标准错误,无法分配内存);
出口(1);
} //复制新的输出
sprintf的(*输出,全名:%S,* names_to_display ++);
的printf(display_names():名称:%s \\ n,*输出++);
}
}
您没有分配给new_output内存,它是由编译器分配。免费是使用在运行时,当你的malloc内存,不释放在编译时,编译器分配的内存。
您new_output是一个局部变量,将被释放,当它超出范围,即在它的声明了函数的右括号。
I have written a problem to practice pointers and allocating memory.
However, I am getting a stack dump when I free the memory. Am I freeing in the correct place? Is there anything else wrong with my program that could make it unsafe?
void display_names(char **names_to_display, char **output);
int main(void)
{
char *names[] = {"Luke", "John", "Peter", 0};
char **my_names = names;
char *new_output[1024] = {0};
size_t i = 0;
// Print the ordinal names
while(*my_names)
{
printf("Name: %s\n", *my_names++);
}
my_names = names; /* Reset */
display_names(my_names, new_output);
// Print the updated names
while(new_output[i])
{
printf("Full names: %s\n", new_output[i]);
i++;
}
// Free allocated memory
free(new_output);
getchar();
return 0;
}
void display_names(char **names_to_display, char **output)
{
while(*names_to_display)
{
*output = (char*) malloc(strlen("FullName: ") + strlen(*names_to_display) + 1);
if(!*output)
{
fprintf(stderr, "Cannot allocate memory");
exit(1);
}
// Copy new output
sprintf(*output, "FullName: %s", *names_to_display++);
printf("display_names(): Name: %s\n", *output++);
}
}
You didn't allocate the memory for new_output, it was allocated by the compiler. free is for use when you malloc memory at runtime, not for freeing memory allocated by the compiler at compile time.
Your new_output is a local variable and will be 'released' when it goes out of scope, i.e. at the closing brace of the function in which it's declared.
这篇关于而错误使用C释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!