Strings in C need to be NUL terminated. This means you need to add a zero value byte to the end of the string to indicate the end of the string. Because you have no indication of the end of the string when you view/print the value you are reading on past the end of your array into whatever memory is after it.
If the source data contains a NUL terminator you can simply allocate and copy 1 more byte, but assuming it is a fixed length field with no NUL termination you will need to manually add one:
data = new char[lengthOfParam+1];
memcpy(data, &buffer[offset], lengthOfParam);
data[lengthOfParam] = 0;
Also further more looking at this line you posted:
obj[1] = data;
I maybe wrong here and sorry if I am but I strongly suspect this line is not doing what you think it is. This will store a pointer to your string in obj[1]
not copy the data from your string. Hence if you delete data
, obj[1]
would no longer be valid either.
2
solved Junk values in char* variable