下面的伪代码,但有谁知道为什么这会破坏堆?urlencode 函数是在其他地方下载的标准库函数,并且似乎按设计运行。在实际代码中,我使用的是动态大小的 char 数组,这就是 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;
}
谢谢。