1

最初に私のコードを見てください.オンラインジャッジでランタイムエラー(sigsegv)が発生していますが、私のコンピューターでは問題なく動作します.エラーを見つけるのを手伝ってください.

制約は次のとおりです。

0< t1 <1000000

0<数値<100000000

#include<stdio.h>

#include<malloc.h>

int *a;

int main()

{

   a = malloc(sizeof(int)*100000000);



   int  t=3,j,k1,k=1,n=0,i,t1,num;



   for(i=1;i<10000;i++)

      {

                  // m=i*i;

                   n=n+t;

                   for(j=i*i;j<=n;j++)



                                    a[j]=k;



                   k++;

                   t=t+2;



     }

  scanf("%d",&t1);



   for(k1=0;k1<t1;k1++)

   {

        scanf("%d",&num);

        printf("%d\n",a[num]);

   }

  free(a);

  //getch();

   return 0;

}

valgrind を使用してこの単純なコードを実行しました。次の出力が得られました。私はvalgrindの初心者なので、どういう意味か教えてください。

singu@singu-Studio-1450 ~ $ valgrind --leak-check=yes ./doors
==4732== Memcheck, a memory error detector
==4732== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==4732== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
==4732== Command: ./doors
==4732== 
==4732== Warning: set address range perms: large range [0x51c3040, 0x1cf3b440)     (undefined)
==4732== Invalid write of size 4
==4732==    at 0x400662: main (doors.c:16)
==4732==  Address 0x1cf3b440 is 0 bytes after a block of size 400,000,000 alloc'd
==4732==    at 0x4C28FAC: malloc (vg_replace_malloc.c:236)
==4732==    by 0x400605: main (doors.c:6)
==4732== 
^C==4732== 
==4732== HEAP SUMMARY:
==4732==     in use at exit: 400,000,000 bytes in 1 blocks
==4732==   total heap usage: 1 allocs, 0 frees, 400,000,000 bytes allocated
==4732== 
==4732== LEAK SUMMARY:
==4732==    definitely lost: 0 bytes in 0 blocks
==4732==    indirectly lost: 0 bytes in 0 blocks
==4732==      possibly lost: 0 bytes in 0 blocks
==4732==    still reachable: 400,000,000 bytes in 1 blocks
==4732==         suppressed: 0 bytes in 0 blocks
==4732== Reachable blocks (those to which a pointer was found) are not shown.
==4732== To see them, rerun with: --leak-check=full --show-reachable=yes
==4732== 
==4732== For counts of detected and suppressed errors, rerun with: -v
==4732== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
4

1 に答える 1

1

Valgrind は基本的に、ここで 2 つのことを伝えます。

1° 割り当てていないメモリ位置に書き込んでいます。これがメッセージの意味invalid writeです。この書き込みはサイズ 4 (整数) で、doors.c の 16 行目で発生します。
これがおそらくセグメンテーション違反の原因です。私の推測では、あなたの a[j] は j のいくつかの値に対して配列の範囲外にあるため、それを適切にチェックする必要があります (より具体的には、配列は 0 からインデックス付けされているため、配列 a の範囲はサイズ s は a[0] から a[s-1] まで)。
問題があるかどうかを確認するには、j を出力して 10,000 未満かどうかを確認する必要があります。

2° 終了時に、1 つの割り当てを実行しましたが、解放は 0 でした。したがって、割り当てた 400,000 バイトを解放しません。ただし、終了時にまだポインターがあるため、still reachable.

于 2012-08-24T10:26:38.613 に答える