下面的伪代码,但是有人知道为什么这会破坏堆吗? urlencode 函数是在其他地方下载的标准库函数,并且看起来按设计运行。在实际代码中,我使用动态大小的字符数组,这就是 main 中需要 malloc 的原因。
/* Returns a url-encoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
char *urlencode(char *str) {
//char *pstr = str, *buf = malloc(strlen(str) * 3 + 1), *pbuf = buf;
char *pstr = str, *buf = malloc(strlen(str) * 3 + 1), *pbuf = buf;
while (*pstr) {
if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
*pbuf++ = *pstr;
else if (*pstr == ' ')
*pbuf++ = '+';
else
*pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
pstr++;
}
*pbuf = '\0';
return buf;
}
int testFunction(char *str) {
char *tmpstr;
tmpstr = urlencode(str);
// Now we do a bunch of stuff
// that doesn't use str
free(tmpstr);
return 0;
// At the end of the function,
// the debugger shows str equal
// to "This is a test"
}
int main() {
char *str = NULL;
str = malloc(100);
strcpy(str, "This is a test");
testFunction(str);
free(str); // Debugger shows correct value for str, but "free" breaks the heap
return 0;
}
谢谢。
最佳答案
我猜测 str
已经被 free(tmpstr);
释放了 - 请看看 urlencode
的行为 -功能。看起来它不会生成新字符串作为返回值,而是将(更改后的)输入字符串传回。
关于c - 将 char 传递给函数会破坏堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12806378/