Question: I've been trying to get this C code to work. I need to take any number of string command line arguments and concatenate them together,
I've been trying to get this C code to work. I need to take any number of string command line arguments and concatenate them together, then print the string. Sometimes it works and sometimes it doesn't, and it often has memory leaks. I've tried debuggers but I can't make any further progress with them on my own. I'm looking for any sort of advice on what I did wrong?
#include
/* print out an error message and exit */ void my_error(char *s) { perror(s); exit(1); }
/* Concatnate two strings. * Dynamically allocate space for the result. * Return the address of the result. */ char *my_strcat(char *s1, char *s2) { char *p = malloc(sizeof(*s2)+sizeof(*s1)); strcat(p, s1); strcat(p, s2); return p;
int main(int argc, char *argv[]) { char *s;
s = my_strcat("", argv[0]);
for (int i = 1; i < argc; i ++) { s = my_strcat(s, argv[i]); }
printf("%s ", s); free(s);
return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
