0

This causes a segmentation fault:

char str1[60];
char**array;

array=malloc( str_nos * sizeof(char *) );
array[i]=malloc( str_len * sizeof(char *) );

strcat(array[i],str1);
strcat(array[i]," ");

str1 is taken from scanf and it's shorter than 60 characters. array[i] is from a dynamic array of strings.

Do you have any idea of what causes the problem? It happens only for a great amount of scanfs.

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
harp
  • 29
  • 5

3 Answers3

3

At least two possibilities:

  • If the buffer pointed to by array[i] doesn't hold enough space, then you will overwrite the end of the buffer, which will often result in a seg-fault.

  • One of the strings isn't properly null-terminated, so strcat just starts walking through memory.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

Either array[i] is pointing to nowhere, or the length of the buffer pointed by array[i] is insufficient.

EDIT: According to the code you posted, the buffer pointed by array[i] initially contains uninitialized garbage. You can't apply strcat to a destination buffer that contains uninitialized garbage.

Either make your buffer to hold an empty string before trying to strcat anything to it

array[i][0] = '\0';
strcat(array[i],str1);
strcat(array[i]," ");

or, alternatively, start with strcpy and then do strcat

strcpy(array[i],str1);
strcat(array[i]," ");
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0
array[i]=malloc( str_len * sizeof(char *) );

What's i here? If i is not in the range [0,str_len), then you are accessing memory that you may not have permission to use...

dmckee --- ex-moderator kitten
  • 98,632
  • 24
  • 142
  • 234