【发布时间】:2014-07-10 17:54:13
【问题描述】:
这是我的情况:
main 根据字符串分配内存,并通过传递地址调用函数。然后该函数适当地调整传递的内存大小以容纳更多数据。之后,当我尝试释放内存时,出现堆错误。
代码如下:
typedef char * string;
typedef string * stringRef;
/**************************
main
**************************/
int main()
{
string input = "Mary had";
string decoded_output = (string)calloc(strlen(input), sizeof(char));
sprintf(decoded_output, "%s", input);
gen_binary_string(input, &decoded_output);
free(decoded_output); /*this causes issue*/
return 0;
}
void gen_binary_string(string input,stringRef output)
{
int i=0, t=0;
size_t max_chars = strlen(input);
/*
the array has to hold total_chars * 8bits/char.
e.g. if input is Mary => array size 4*8=32 + 1 (+1 for \0)
*/
string binary_string = (string)calloc((BINARY_MAX*max_chars) + 1, sizeof(char));
int offset = 0;
/* for each character in input string */
while (*(input+i))
{
/* do some binary stuff... */
}
/* null terminator */
binary_string[BINARY_MAX*max_chars] = '\0';
int newLen = strlen(binary_string);
string new_output = (string) realloc((*output), newLen);
if (new_output == NULL)
{
printf("FATAL: error in realloc!\n");
free(binary_string);
return;
}
strcpy(new_output, binary_string);
(*output) = new_output;
free(binary_string);
}
【问题讨论】:
-
我建议您使用术语“按地址传递”而不是“按引用传递”。 C++ 对什么是引用有一个特定的概念,由于 C 和 C++ 彼此有些接近,所以不用同一个词来描述 C 概念可以省去您的麻烦。
-
是的,我解决了我的问题,谢谢!
-
停止使用指针类型定义,它们使代码难以阅读
-
@zneak 我认为使用“通过引用传递”很好,因为该术语适用于许多语言;虽然你偶尔会遇到那些似乎不愿意承认他们知道你在说什么的超级学究
-
对不起,McNabb 先生,如果我的问题打扰到您了!!
标签: c memory memory-leaks heap-memory realloc