2011-12-24 8 views
1

"realloc()"を使用するとValgrindが "無効な空きまたは削除"を生成するのはなぜですか?

valgrind --tool=memcheck --leak-check=yes --show-reachable=yes a.out 

に従い、valgrindのによって生成されたエラー情報が

==6402== Memcheck, a memory error detector. 
==6402== Copyright (C) 2002-2005, and GNU GPL'd, by Julian Seward et al. 
==6402== Using LibVEX rev 1575, a library for dynamic binary translation. 
==6402== Copyright (C) 2004-2005, and GNU GPL'd, by OpenWorks LLP. 
==6402== Using valgrind-3.1.1, a dynamic binary instrumentation framework. 
==6402== Copyright (C) 2000-2005, and GNU GPL'd, by Julian Seward et al. 
==6402== For more details, rerun with: -v 
==6402== 
dinesh 
vignesh 
==6402== Invalid free()/delete/delete[] 
==6402== at 0x4905E12: realloc (vg_replace_malloc.c:306) 
==6402== by 0x400539: main (in /user/gur29597/mysourcecode/VMake/a.out) 
==6402== Address 0x7FF000830 is on thread 1's stack 
vishwa 
==6402== 
==6402== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 1) 
==6402== malloc/free: in use at exit: 0 bytes in 0 blocks. 
==6402== malloc/free: 1 allocs, 1 frees, 3 bytes allocated. 
==6402== For counts of detected errors, rerun with: -v 
==6402== All heap blocks were freed -- no leaks are possible. 

次のように私のコードは、

#include<stdio.h> 

int main() 
{ 
    char *name[2]; 

name[0]="dinesh"; 

name[1]="vignesh"; 

    printf("%s\n%s\n",name[0],name[1]); 

    realloc(name,3); 

    name[2]="vishwa"; 

    printf("%s\n",name[2]); 

return 0; 
} 
+0

以下の正解に加えて、 'realloc()'にサイズをバイト単位で渡すように注意する必要があります。 'name 'が' malloc() 'で割り当てられたブロックを正しく指していても、' realloc(name、3); 'はあなたが望むことをしません。 –

答えて

6

プログラムの原因未定義の動作とvalgrindが正しく指摘しています。

参考:

C99標準7.20.3.4-1:realloc関数:

あらすじ

の#include
void *型のrealloc(ボイド* ptrに、size_tのサイズ);

パラ3:

ptrがヌルポインタである場合、realloc関数は、特異的EDサイズのmalloc関数のように振る舞います。そうでなければ、callocmalloc、またはrealloc関数によって返されたポインタにifptrが一致しないか、またはfreeまたはrealloc関数の呼び出しによって領域が割り当て解除された場合、その動作は未定義のです。 newオブジェクトのメモリが割り当てられない場合、古いオブジェクトは割り当て解除されず、その値は変更されません。あなたのケースでポインタがreallocに渡されることを

注意もcallocmallocまたはので、標準の未定義の動作によって義務付け要件を破るreallocを呼び出すことによって受信されませんでしたヌルANSではありません。

5

であるとしてのrealloc()を使用している間、私はvalgrindのとそれをチェックがmallocまたはreallocから返されたポインタに対してのみreallocを使用できます。つまり、あなたのプログラムは間違っています。

+0

+1。また、その特定のエラーの理由は、reallocが簡単なfree()+ malloc()として実装されることがあるためです。 – kperryua

関連する問題