2014-06-27 63 views
0

我試圖回填我對C內存管理的知識。我主要來自腳本和託管背景,我想了解更多關於C和C++的知識。爲此我一直在讀了幾本書,其中包括其中包括使用realloc修剪空格的字符串的這個例子:Valgrind報告無效Realloc

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

char* trim(char* phrase) 
{ 
    char* old = phrase; 
    char* new = phrase; 

    while(*old == ' ') { 
    old++; 
    } 

    while(*old) { 
    *(new++) = *(old++); 
    } 

    *new = 0; 

    return (char*)realloc(phrase, strlen(phrase)+1); 
} 

int main() 
{ 
    char* buffer = (char*)malloc(strlen(" cat")+1); 
    strcpy(buffer, " cat"); 

    printf("%s\n", trim(buffer)); 

    free(buffer); 
    buffer=NULL; 

    return 0; 
} 

我忠實地複製的例子,並與c99 -Wall -Wpointer-arith -O3 -pedantic -march=native編譯。我沒有收到任何編譯錯誤,並且該應用程序運行並遵循本書所承諾的內容,但是當我針對valgrind運行它時,出現無效的錯誤realloc

==21601== Memcheck, a memory error detector 
==21601== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. 
==21601== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info 
==21601== Command: ./trim 
==21601== 
==21601== Invalid free()/delete/delete[]/realloc() 
==21601== at 0x402B3D8: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) 
==21601== by 0x804844E: main (in /home/mo/programming/learning_pointers/trim) 
==21601== Address 0x4202028 is 0 bytes inside a block of size 6 free'd 
==21601== at 0x402C324: realloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) 
==21601== by 0x80485A9: trim (in /home/mo/programming/learning_pointers/trim) 
==21601== by 0x804842E: main (in /home/mo/programming/learning_pointers/trim) 
==21601== 
==21601== 
==21601== HEAP SUMMARY: 
==21601==  in use at exit: 4 bytes in 1 blocks 
==21601== total heap usage: 2 allocs, 2 frees, 10 bytes allocated 
==21601== 
==21601== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1 
==21601== at 0x402C324: realloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) 
==21601== by 0x80485A9: trim (in /home/mo/programming/learning_pointers/trim) 
==21601== by 0x804842E: main (in /home/mo/programming/learning_pointers/trim) 
==21601== 
==21601== LEAK SUMMARY: 
==21601== definitely lost: 4 bytes in 1 blocks 
==21601== indirectly lost: 0 bytes in 0 blocks 
==21601==  possibly lost: 0 bytes in 0 blocks 
==21601== still reachable: 0 bytes in 0 blocks 
==21601==   suppressed: 0 bytes in 0 blocks 
==21601== 
==21601== For counts of detected and suppressed errors, rerun with: -v 
==21601== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0) 

所以請幫助我理解爲什麼它認爲無效的realloc。是垃圾的例子嗎?有什麼我失蹤?我知道根據規範,realloc期望指針已經由malloc創建,那麼是因爲realloc在另一個函數中?還是valgrind困惑,因爲他們在不同的功能?我不是一個完全白癡(大多數日子),但現在我有點覺得沒有看到這個問題。

在此先感謝!

回答

4

您正在嘗試free原始指針,而不是realloc d一個。你可以通過以下方式修復它:

buffer = trim(buffer) 
+0

它就在那裏。看,一時失明。我認爲它必須是我正在做的事情,但我只是沒有看到它。真棒。非常感謝! –