Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Memory test returns weird output

Tags:

c++

memory

Slackware here. I was just messing around with memory stuff and pointers... I wanted to learn a bit more about those, so I made an array in c++, and looked up the memory address of the first item in it...:

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

It outputted this: http://pastebin.com/K0HAL5nJ The whole code:

#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;
}

I am a complete beginner in c++ and do not understand why this happens at all... I know that this sort of code is not supposed to... be, but still, could anyone please explain what happened there?

like image 855
Slackware Avatar asked Dec 27 '22 07:12

Slackware


2 Answers

It's undefined behaviour. &foo[0] gives you the address of the first std::string object, which you then subtract 4 from. From §5.7 Additive operators:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

Undefined behaviour means you could experience anything. What is probably happening is some area of memory, four positions before the beginning of the array, that is not a valid std::string object is being treated as a std::string. This is bound to lead to ugly things happening.

like image 191
Joseph Mansfield Avatar answered Jan 30 '23 08:01

Joseph Mansfield


Pointer addition and element size


When you add an integer to a pointer, the integer is multiplied by the element size of the type that the pointer points to.

// 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

like image 32
pexeer Avatar answered Jan 30 '23 06:01

pexeer