0

As the title indicates, this should be very easy. I don't understand why, but I'm getting a Bus error: 10 when I run this.

This should be so easy! But I can't seem to solve it.... ugh. Please help.

#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]);
}   
}
Meshach
  • 315
  • 1
  • 2
  • 16

3 Answers3

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

You're allocating to string[wordCount] and then you're incrementing wordCount. Then you proceed to strcpy to this new, unallocated element, which is illegal.

Increment wordCount after strcpy instead.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
0

Another problem you should have is that if you read more than 20 lines, you will make an illegal memory access since you are declaring an array of char pointers with 20 positions:

char *string[20];

You should reconsider the loop:

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

Hernan Velasquez
  • 2,770
  • 14
  • 21
0

You should ever check for an array-(index)-overflow like:

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;
}

Note that scanf will ever breaks on all whitespaces and you clear the input-buffer after all scanf/fgets(stdin) actions.

user411313
  • 3,930
  • 19
  • 16