输出会吐出两个额外的控制字符,可能是内存损坏错误? [英] Output spits two extra control characters, possibly a memory corruption bug?

查看:89
本文介绍了输出会吐出两个额外的控制字符,可能是内存损坏错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下程序test.cc:

#include <iostream>
unsigned char bogus1[] = {
  // Changing # of periods (0x2e) changes output after periods.
  0x2e, 0x2e, 0x2e, 0x2e
};
unsigned int bogus2 = 1816; // Changing this value changes output.

int main()
{
  std::clog << bogus1;
}

我用以下方法构建它:

g++ -g -c -o test.o test.cc; g++ -static-libgcc -o test test.o

使用g ++版本3.4.6

我通过valgrind运行它,没有报错.

但是输出中有两个额外的控制字符,看起来像这样:

....

最后是一个Control-X和一个Control-G.

如果更改bogus2的值,则会获得不同的控制字符.如果您更改阵列中的周期数,则问题将消失或改变.<​​/p>

我怀疑这是编译器或iostream软件包中的内存损坏错误.

这是怎么回事?

解决方案

在C/C ++中,字符串通常存储为以空值结尾的char数组.

您的无符号char数组不是以空值结尾的.通常情况如下:

unsigned char bogus1[] = {
  0x2e, 0x2e, 0x2e, 0x2e,
  0x00 // terminating NUL byte
};

如果它不是以Null结尾的,则输出将一直持续到找到NUL字节为止,这就是为什么它输出放置在数组后面的内存中的值的原因,例如int bogus2(十六进制的0x00000718,存储在小尾数格式=> 0x18 = Ctrl-X,0x07 = Ctrl-G,0x00结束输出)

I have the following program test.cc:

#include <iostream>
unsigned char bogus1[] = {
  // Changing # of periods (0x2e) changes output after periods.
  0x2e, 0x2e, 0x2e, 0x2e
};
unsigned int bogus2 = 1816; // Changing this value changes output.

int main()
{
  std::clog << bogus1;
}

I build it with:

g++ -g -c -o test.o test.cc; g++ -static-libgcc -o test test.o

Using g++ version 3.4.6

I run it through valgrind and nothing is reported wrong.

However the output has two extra control characters and looks like this:

....

That's a control-X and a control-G at the end.

If you change the value of bogus2 you get different control characters. If you change the number of periods in the array the issue goes away or changes.

I suspect it is a memory corruption bug in the compiler or iostream package.

What is going on here?

解决方案

In C/C++, a string is usually stored as a null-terminated char array.

Your unsigned char array isn't null-terminated. Usually it would look something like this:

unsigned char bogus1[] = {
  0x2e, 0x2e, 0x2e, 0x2e,
  0x00 // terminating NUL byte
};

If it isn't null-terminated, output will continue until a NUL byte is found, that's why it outputs values that are placed in the memory behind your array, like the int bogus2 (which is 0x00000718 in hex, stored in little endian format => 0x18 = Ctrl-X, 0x07 = Ctrl-G, 0x00 ends the output)

这篇关于输出会吐出两个额外的控制字符,可能是内存损坏错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆