Strcat changing the wrong variable

I am struggling to understand what's happening when I use strcat to join two variables, which results in the desired char array plus the undesirable change to a different char array.

I've reduced the problem to the code example below. Normally, the #define is in another file for security purposes.

char wxServer[] = "";
char wxAPI[] = "/dowxstuff/now?";
#define ID "Login"

void setup() {

void loop() {
    strcat(wxAPI, ID);


This results in the following:

12:54:55.783 ->
12:54:55.783 -> /dowxstuff/now?          
12:54:55.783 -> Login
12:54:55.783 -> /dowxstuff/now?Login
12:54:55.783 -> ogin <====== what happened to, and what ate the letter L?
12:54:55.783 -> Login

I still have my C++ training wheels so I assume I'm just making a bonehead mistake here.

you need to allocate enough memory for the strcat to not overflow your buffer....

when you do

char wxAPI[] = "/dowxstuff/now?";

you only allocated in the wxAPI buffer enough bytes for the characters of "/dowxstuff/now?" (plus one hidden trailing null character). so whatever you try to add at the end will be written in memory just after, and that will crash the content of other variables


char wxAPI[100] = "/dowxstuff/now?";

and now you have plenty of room reserved in the buffer after the text, and you can concatenate (that will fill in the bytes after your text).

the best practice is to use strncat() which can take into account the buffer size, this way you won't overflow

char wxAPI[30] = "/dowxstuff/now?";

I wish I had learned to program in C first; maybe then memory management would be more obvious to me.

Anyway this is working fine now. Thanks for the tip and perfect explanation!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.