0

下面的伪代码,但有谁知道为什么这会破坏堆?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;
}

谢谢。

4

2 回答 2

1

I would guess that str was already freed by free(tmpstr); - please have a look at the behavior of the urlencode-function. It seems like it does not generate a new string as return value, but passes the (changed) input string back.

于 2012-10-09T18:55:26.660 回答
0

问题原来是 str 的初始 malloc 执行为 0 的大小计算问题。感谢您的评论,不幸的是,没有办法将答案真正标记为评论。

如果这是关闭它的不正确方法,请告诉我。

于 2012-10-09T21:58:28.920 回答