Psudo 코드가 나옵니다. 그러나 왜 이것이 힙을 깨뜨리는 지 알 수 있습니까? urlencode 함수는 다른 곳에서 다운로드 된 표준 라이브러리 함수이며 설계된대로 작동하는 것으로 보입니다. 실제 코드에서 동적 크기 char 배열을 사용하고 있으므로 main에서 malloc 요구 사항의 이유.함수에 char을 건네 주면 아래 코드
/* 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;
}
감사합니다.
segfault가 있습니까? 또는 이중 자유/힙 손상 오류가 구체적으로? – PherricOxide
여기에 문제 없지만'char'가 ASCII 범위를 벗어나면'to_hex (* pstr >> 4)'는 문제를 일으킬 수 있습니다.'0xF '로도 마스크하는 것이 더 안전합니다. –
나를 위해 잘 작동하고 Valgrind는 오류를 발생시키지 않습니다. '// 이제 str을 사용하지 않는 많은 것들을 처리합니까?'라는 코드가 힙을 손상시키지 않았습니까? Valgrind에서 실행 해 보셨습니까? –