c - 将 char 传递给函数会破坏堆

标签 c char heap-memory heap-corruption

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

相关文章:

c# - 用压降控制遥控车

c - POSIX API 和 SOLID 设计原则

java - 在 Java 中将用户输入的单词转换为 unicode 数组

c - 如何将结构类型转换为分配的 char 内存空间

C++ 删除对象作为引用

c - ubuntu 14.04.1 x64 上 Codelite 6.1 中的 Pthreads

c - 在 B 树中查找第 k 个键的算法?

c++ - 怪异 : pointer address doesn't change but contents off by 1

c++ - 无法将 char 指针转换为整数

C++ 在指针范围结束后访问堆上的对象