I have the following code, that declares a char data[]
with simple JSON data. ({"x":123,"y":137}
) 17 chars long.
On my main function I then try to copy the char data[]
char by char and concatenate to a new string using strcat
function.
When I print the char that I want to concatenate it appears to be the valid char, but when I print the final string, it is wrong.
Code:
#include <stdio.h>
#include <string.h>
int getDataLength(){
return 17;
}
static char data[] = {'{','"','x','"',':','1','2','5',',','"','y','"',':','1','3','7','}'};
char getData(int i){
return data[i];
}
int main() {
int dataLength = getDataLength();
char data[dataLength + 1];
for(int i=0 ; i < dataLength ; i++){
char chr = getData(i);
// --- looking good ---
printf("%c",chr);
strcat(data,&chr);
}
data[dataLength] = '\0';
// --- broken string ---
printf("\n%s",data);
}
Output:
{"x":125,"y":137}
(���{"x":1%
What am I missing?
You should look at your compiler warnings.
strcat(data,&chr);
strcat
expects two strings as parameters. Your second parameter is no string but only a single character.
The nul-termination is missing and you copy random garbage data.
Additionally you don't initialize data
before you start adding to it.
Both errors cause undefined behaviour in your program.