簡體   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