2011-07-04 3 views
5

私は小さなコードを持っています。私は-lmcheckでコンパイルしました。同じようなエラーが発生したコードをデバッグしようとしています。メモリClobberingエラー

私はこのコードを実行したときに、私はこのエラーを取得:

memory clobbered before allocated block 

誰かがfree(ptr)が私にこのエラーがスローされます理由を説明できますか?

他にどのようにポインタを解放できますか?

ありがとうございました。

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h> 
#define LEN 5 


int main(int argc, char *argv[]){ 

    char *ptr = NULL; 

    ptr = (char *) malloc(LEN+1);// +1 for string 
    strcpy(ptr, "hello"); 

    int i = 0; 
    for(i = 0; i<LEN; i++) 
    { 
     printf("ptr[%d] = %c\n", i, ptr[i]); 
     ptr++; 
    } 
    free(ptr); 


    return 0; 
} 
+0

また、http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858をご検討ください。 – unwind

答えて

8

ptrをインクリメントしているため、指すアドレスが変更されています。あなたはそれをすることはできません。あなたのケースでは

、別々のポインタを持っている、のはchar * p = ptrを言うとpはあなたが後でfree(ptr)ので、そのままptrをすることができます残して、あなたの操作を行うことができます。

EDITコードをもう一度見て、私があなたがしてはならないときにptr++をやっていることがわかりました。 ptr[i]のような配列の文字にアクセスしている場合、ptrポインタを混乱させると、ベースアドレスが変更され、ptr[i]で文字にアクセスすると、予期しない結果が生じる可能性があります。

単純にその行(ptr++)を削除すると、コードが魔法のように機能します。 あなたは、ポインタの概念を探求し、別の解決策を試してみたい場合は、あなたのコードは次のようになりませんでした:ptrは、もはやあなたが割り当てられたメモリのベースを指しているので

int main(int argc, char *argv[]){ 

    char *ptr = NULL; 
    char * p; 

    ptr = (char *) malloc(LEN+1);// +1 for string (please check for NULL) 
    p = ptr; 

    strcpy(ptr, "hello"); 

    int i = 0; 
    while (*p) // note how I changed it to a while loop, C strings are NULL terminated, so this will break once we get to the end of the string. What we gain is that this will work for ANY string size. 
    { 
     printf("ptr[%d] = %c\n", i++, *p); // here i dereference the pointer, accessing its individual char 
     p++; 
    } 
    free(ptr); 


    return 0; 
} 
+1

優秀な説明!余分なマイルに行くことに感謝します。 –

2

を。あなたがptrをインクリメントした後

1

また、表現ptr[i]あなたが期待するかもしれないものは戻りません。それが出力が "hlo"で始まる理由です。

1

コメントの回答を見つけます。 いくつかのメモリを割り当てると、通常、メモリ管理フレームワークは、割り当てられたメモリ領域にさらに多くの情報(ヘッダーとフッターと言うことができます)を追加することによって、メモリの管理を行います。このメモリを解放すると、不要な/無効なメモリアクセスを検出するために同じ情報が照合されます。

int main(int argc, char *argv[]){ 

    char *ptr = NULL; 
    char* temp = NULL;   // Have a temp pointer. 

    ptr = (char *) malloc(LEN+1);// +1 for string 
    strcpy(ptr, "hello"); 

    temp = ptr;     // manipulate temp pointer instead of ptr itself 

    int i = 0; 
    for(i = 0; i<LEN; i++) 
    { 
     printf("ptr[%d] = %c\n", i, temp[i]); 
     temp++;     // Why you are incrementing this? Just to print, there is no need of this. 
    } 
    free(ptr); 


    return 0; 
}