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_string
function:
strncat(str, str2, bufferSize);
Your str
only has room for seven bytes and it is already full before you try to append str2
to it. You're getting lucky with this:
char str1[10] = "Hello";
as you still don't have enough space allocated to append "World"
to it; you're also missing the trailing space on this version of str1
but that's not relevant to your segfault. Your concat_string
should be copying str
directly to destination
and then appending str2
to destination
. This would also avoid altering the str
and str2
arguments and that would be more polite; you also don't pass the sizes of the str
and str1
arrays so there's no way to know if there is room to append anything to them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.