1

問題のコードは次のとおりです。

long number = atol(argv[1]);
long prime_limit = number / 2;
int * primes = malloc(sizeof(int) * prime_limit);
long i;
for (i = 2; i <= prime_limit; i++) {
    primes[i] = 1; # This is line 16
}

エラーは次のとおりです。

==9318== Invalid write of size 4
==9318==    at 0x40065B: main (003.c:16)
==9318==  Address 0x8 is not stack'd, malloc'd or (recently) free'd
==9318== 
==9318== 
==9318== Process terminating with default action of signal 11 (SIGSEGV)
==9318==  Access not within mapped region at address 0x8
==9318==    at 0x40065B: main (003.c:16)
==9318==  If you believe this happened as a result of a stack
==9318==  overflow in your program's main thread (unlikely but
==9318==  possible), you can try to increase the size of the
==9318==  main thread stack using the --main-stacksize= flag.
==9318==  The main thread stack size used in this run was 8388608.

エラーはmallocの使用方法にあるはずだと思いますが、よくわかりません。argv[1]の値は600851475143です。

4

3 に答える 3

4

配列は0Cで-originです:

i <= prime_limit;

する必要があります

i < prime_limit;

それ以外の場合atolは安全ではなく、エラー検出を行うことができません。strtol文字列をに変換するために使用しlongます。

于 2013-02-27T23:09:39.153 に答える
2

割り当てが失敗します:

=9318==  Address 0x8 is not stack'd, malloc'd or (recently) free'd

...割り当てを試みているので、どの種類の意味がありますか、600851475143 * 4/2、または1201702950288バイト、または1.2TB。

primesしたがってNULL、を実行するときにそれを逆参照しようとしているためprimes[i]、未定義の動作が発生します。

比較のために、適切に割り当てられたメモリチャンクの境界を超えて書き込みを行っている場合、Valgrindは次のような出力を提供します。

==10088==  Address 0x51f104c is 0 bytes after a block of size 12 alloc'd

mallocの戻り値を常に確認してください。

int * primes = malloc(sizeof(int) * prime_limit);
if (primes == NULL) {
    perror("Allocation failure!");
    /* handle error */
}

そして、一度に1TBを割り当てようとしないでください...

于 2013-02-28T00:18:11.870 に答える
0

ouah さんの投稿に加えて、malloc() によって返されるポインター値を確認する必要があると思います。要求した量のメモリを割り当てることができなかった可能性があります。

于 2013-02-27T23:43:33.880 に答える