繁体   English   中英

C ++内存测试返回奇怪的输出

[英]C++ Memory test returns weird output

Slackware在这里。 我只是搞乱内存和指针...我想学习更多关于那些,所以我用c ++创建了一个数组,并查找了第一项的内存地址......:

string foo[3] = {"a", "b", "c"};
cout << *(&foo[0]-4) << endl;

它输出: http//pastebin.com/K0HAL5nJ整个代码:

#include <iostream>

using namespace std;

int main()
{
    string foo[3] = {"a", "b", "c"};
    cout << &foo[0] << " minus " << &foo[1] << " equals " << int(&foo[0])-int(&foo[1]) << endl;
    cout << *(&foo[0]-4) << endl;
    cout << "Hello world!" << endl;
    return 0;
}

我是c ++的完全初学者,并且不明白为什么会发生这种情况...我知道这种代码不应该......但是,仍然可以请任何人解释那里发生的事情吗?

这是未定义的行为。 &foo[0]为您提供第一个std::string对象的地址,然后从中减去4。 来自§5.7添加剂运算符:

如果指针操作数和结果都指向同一个数组对象的元素,或者指向数组对象的最后一个元素,则评估不应产生溢出; 否则,行为未定义。

未定义的行为意味着您可以体验任何事物。 可能发生的是一些内存区域,在数组开始之前的四个位置,这不是一个有效的std::string对象被视为std::string 这必将导致丑陋的事情发生。

指针添加和元素大小


向指针添加整数时,整数乘以指针指向的类型的元素大小。

// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

  cout << *(&foo[0]-4) << endl;

这段代码是打印foo [-4]

试试这段代码。

 cout << *(&foo[4]-4) << endl;

这将打印foo [0]

 T * p;
 int n;

p+n意味着的地址p添加的sizeof(T *)* n个

指针添加和元素大小
向指针添加整数时,整数乘以指针指向的类型的元素大小。

// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

您正在访问一些超出您分配的数组的地址空间的内存,这会导致未定义的行为。

 string foo[3] = {"a", "b", "c"};
 cout << &foo[0] << " minus " << &foo[1] << " equals " 
      << int(&foo[0])-int(&foo[1]);

 &foo[0] get the memory address of "a",
 &foo[1] get the memory address of "b";
 the output is OK since both address are in range of foo's address space

cout << *(&foo[0]-4) << endl;
 You tried to get the value at address of ("a" -4),
since this address is outside the address of foo, it is undefined behavior. 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM