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

私はそれstrがすでに解放されていると思いfree(tmpstr);ます - 関数の動作を見てくださいurlencode。戻り値として新しい文字列を生成しないようですが、(変更された) 入力文字列を返します。

于 2012-10-09T18:55:26.660 に答える
0

この問題は、 str の初期 malloc のサイズ計算が 0 として実行されるという問題であることが判明しました。コメントありがとうございます。残念ながら、回答をコメントとして実際にマークする方法はありません。

これがこれを締めくくる不適切な方法である場合は、お知らせください。

于 2012-10-09T21:58:28.920 に答える