在字符*变量值的垃圾 [英] Junk values in char* variable
问题描述
code:
char* data = NULL;
data = new char[lengthOfParam]; //lengthOfParam = 3
//after allocation **data = ¥¥¥¥Ü\r**
memcpy(data,&buffer[offset],lengthOfParam); //**data = pki¥Ü\r**
为什么我收到的垃圾值?如何避免或删除这些额外的价值BCS,如果我尝试这个值分配给任何其他数组
例如:
Why i am getting that junk values??? How to avoid or remove those extra values bcs if i try to assign that value to any other array ex:
obj[1] = data;
然后junk'll整个价值分配给该变量。
then the whole value with junk'll be assigned to that variable.
推荐答案
在C字符串必须NUL终止。这意味着你需要一个零值字节添加到字符串的结尾表示字符串的结尾。因为你有没有字符串结束的迹象,当你查看/打印您正在阅读以往阵列的一端插入任何内存值后。
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.
如果源数据包含NUL终结你可以简单地分配和复制1字节以上,但假设它是一个没有终止NUL固定长度字段,您将需要手动添加一个:
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;
我在这里也许错了,对不起,如果我是,但我强烈怀疑该行没有做什么,你认为它是。这将一个指向您的字符串存储在 OBJ [1]
不会从您的字符串复制数据。因此,如果您删除数据
, OBJ [1]
将不再有效无论是。
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.
这篇关于在字符*变量值的垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!