I am trying to construct a string message. It should start with a BEGIN-tag and end with en END-tag. I am trying to concatenate the BEGIN-tag (declared as a #define) with a string and then with the END-tag.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BEGIN "@@"
#define END "CCC"
int main(void) {
char *beg;
char *end;
int i = 0;
beg = malloc(sizeof(BEGIN));
end = malloc(sizeof(END));
beg = strcpy(beg,BEGIN);
end = strcpy(end,END);
printf("----------------Begin of Round %i------------------\n",++i);
printf("beg pointer before concat: %s\n", beg);
printf("end pointer before concat: %s\n", end);
printf("BEGIN pointer before concat: %s\n", BEGIN);
printf("END pointer before concat: %s\n", END);
beg = strcat(beg, "Some beautiful message");
// beg = strcat(beg, end);
printf("beg pointer after concat: %s\n", beg);
printf("end pointer after concat: %s\n", end);
printf("BEGIN pointer after concat: %s\n", BEGIN);
printf("END pointer after concat: %s\n", END);
printf("----------------End of Round %i------------------\n\n",i);
return 0;
}
The output that I get is this:
Code:
----------------Begin of Round 1------------------
beg pointer before concat: @@
end pointer before concat: CCC
BEGIN pointer before concat: @@
END pointer before concat: CCC
beg pointer after concat: @@Some beautiful message
end pointer after concat: message
BEGIN pointer after concat: @@
END pointer after concat: CCC
----------------End of Round 1------------------
(1) The main thing that I don't understand is the value of the end pointer after the concat call. Why is it changed to what it is.
(2) Furthermore I do not really understand why I have to use the malloc statements in this case (without them the program crashed)
(3) If you look at the code, there is one statement commented-out. If I run it, it crashes, why?
Thanks for your efforts.