0

タイトルが示すように、これは非常に簡単なはずです。理由はわかりませんが、これを実行すると Bus error: 10 が発生します。

これはとても簡単なはずです!でも、なかなか解けなくて……うーん。助けてください。

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

main() {

char *string[20];
char buffer[256];

int wordCount = 0;

    while ((scanf("%s", buffer) != EOF)) {
        printf("%s%d\n", buffer, wordCount);
        string[wordCount++] = (char *) malloc (strlen(buffer)+1); 
        strcpy (string[wordCount], buffer);
    }

int j;

printf("There are %d words.\n", wordCount+1);

for (j = 0; j < wordCount; j++)
{

    printf("%s\n", string[j]);
}   
}
4

3 に答える 3

3
string[wordCount++] = (char *) malloc (strlen(buffer)+1); 
strcpy (string[wordCount], buffer);

に割り当ててからstring[wordCount]、インクリメントしていますwordCount。次に、この新しい未割り当ての要素に進みますがstrcpy、これは違法です。

代わりに後にインクリメントwordCount strcpyます。

于 2012-09-07T21:44:00.950 に答える
0

次のような配列(インデックス)オーバーフローをチェックする必要があります。

int main() {

char *string[20];
char buffer[256];

int j, wordCount = 0;

    while (wordcount<20 && (scanf("%255s", buffer) == 1)) {  /* here */
        printf("%s%d\n", buffer, wordCount+1);
        strcpy( string[wordCount++] = malloc (strlen(buffer)+1, buffer ); 
    }

printf("There are %d words.\n", wordCount+1);

for (j = 0; j < wordCount; j++)
{

    printf("%s\n", string[j]);
}
  return 0;
}

scanf はすべての空白で中断し、すべての scanf/fgets(stdin) アクションの後に入力バッファをクリアすることに注意してください。

于 2012-09-08T07:54:49.593 に答える
0

もう 1 つの問題は、20 行を超える読み取りを行うと、20 の位置を持つ char ポインターの配列を宣言しているため、不正なメモリ アクセスが発生することです。

char *string[20];

ループを再検討する必要があります。

while ((scanf("%s", buffer) != EOF))

于 2012-09-08T04:42:55.240 に答える