#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(int argc, string argv[])
{
string destination = argv[1];
for (int i = 1; i < argc; i++)
{
strcat(argv[i], argv[i+1]);
}
printf("%s\n", destination);
}
I need all strings in argv[ ] to be concatenated together. Following program works but at the end give seg fault (core dumped). How can I avoid that?
Neither
argv[i]has enough space to be able to store an appended string (of course if the appended string is not an empty string).Moreover
argv[argc]is a null pointer. As a result in the for loop in this callthere is used null pointer
argv[i+1]wheniis equal toargc-1that again results in undefined behavior.From the C Standard (5.1.2.2.1 Program startup)
At least you should write
instead of
provided that the array
destinationcan contain all the concatenated strings.You need to allocate dynamically a large enough array that can be able to store all the concatenated strings.
For example
Or as you are using the type alias
stringfor the typechar *then instead ofyou may write