2016-03-27 9 views
0

で私は、知らない:プログラム()私はこのエラーを取得していますなぜ無効なポインタメッセージ

Error in `./prog': free(): invalid pointer: 0x0941600b

このコードあなたのコードで

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

int main() 
{ 
    int test; 
    scanf("%d",&test); 
    while(test) 
    { 
     char *s; 
     int count=0; 
     s=(char *)calloc(10000,sizeof(char)); 
     scanf("%s",s); 
     while(*s) 
     { 
      if(*s=='W') 
       count++; 
      s++; 
     } 
     printf("%d\n",count); 
     free(s); 
     test--; 
    } 
    return 0; 
} 
+1

['malloc()'と 'C 'のファミリの戻り値をキャストしない理由についてのこのディスカッションを参照してください。](http://stackoverflow.com/q/605845/2173917)。 –

答えて

1

を実行中に、あなたは最初

s++; //moving the actually returned pointer 

を行なったし、それから、あなたは

を試してみました

したがって、calloc()によって返された同じポインタを渡していないとします。これによりundefined behaviorが呼び出されます。

C11標準、章を引用し、追加するには§7.22.3.3

[...] if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc , the behavior is undefined.

のでs++calloc()で返されるとfree()に同じを渡すとUBを呼び出したもう同じではありません、元のポインタを変更します。後でfree()にそれを渡すために元のポインタのコピーを保持する必要があります。

  1. Please see this discussion on why not to cast the return value of malloc() and family in C.、言っ

  2. 戻り値を使用する前に、戻り値がcalloc()であることを確認して、関数呼び出しが失敗した場合のNULLポインタの無効化を避ける必要があります。
+1

ご説明いただきありがとうございます。 –

1

freeは、増分した後にsの値で呼び出します。返された値をcallocから保存して、freeに渡す必要があります。

+0

ご説明いただきありがとうございます。 –

関連する問題