[Solved] Strange problem with variable in C program [closed]


The array str, because it doesn’t have an explicit size, is sized to exactly store what it is initialized with. And because an empty string only contains 1 character, namely a terminating null byte, your array is 1 element in size.

This means str isn’t large enough to hold any string that’s not an empty string, so using strcat on it causes the function to write past the end of the array, triggering undefined behavior. In this case, it manifests as writing into another variable which happens to be adjacent to the array in memory.

The array must be sized properly to hold whatever string it might hold, i.e.:

char str[33] = "";

This gives you enough space to store the binary representation of any nonnegative 32 bit integer.

solved Strange problem with variable in C program [closed]