Can anyone explain to me why when initializing a char array, if the array size is left blank, like this
char str1[] = "Hello";
the program will seg fault, but if it is specified like this
char str1[10] = "Hello";
it works fine.
Here is the full program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char concat_string(char str[], char str2[], char destination[], unsigned int bufferSize);
int main(int argc, char *argv[])
{
unsigned int bufferSize = 64;
// Both str1 and str2 must be defined
// or else the program will seg fault.
char str1[] = "Hello ";
char str2[] = "World";
char concatenatedString[bufferSize];
concat_string(str1,str2,concatenatedString,bufferSize);
printf("The concatenated string is: \n%s\n", concatenatedString);
return 0;
}
char concat_string(char str[], char str2[], char destination[], unsigned int bufferSize)
{
char buffer[bufferSize];
strncat(str, str2, bufferSize);
strncpy(buffer,str, bufferSize);
strncpy(destination,buffer,bufferSize);
return *destination;
}
You have a buffer overflow right here in your
concat_stringfunction:Your
stronly has room for seven bytes and it is already full before you try to appendstr2to it. You’re getting lucky with this:as you still don’t have enough space allocated to append
"World"to it; you’re also missing the trailing space on this version ofstr1but that’s not relevant to your segfault. Yourconcat_stringshould be copyingstrdirectly todestinationand then appendingstr2todestination. This would also avoid altering thestrandstr2arguments and that would be more polite; you also don’t pass the sizes of thestrandstr1arrays so there’s no way to know if there is room to append anything to them.