Say you do:
void something()
{
int* number = new int(16);
int* sixteen = number;
}
How does the CPU know the address that I want to assign to sixteen?
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s no magic in your example code. Take this snippet, for example:
Your code with pointers is exactly the same – the computer doesn’t need to know any magic information, it’s just copying whatever’s in
numberintosixteen.As to your comment below:
In practice, on most machines these days, probably neither of them will be in memory, they’ll be in registers. But if they are in memory, then yes, the compiler will emit code that keeps track of all of those addresses as necessary. In this case, they’d be on the stack, so the machine code would be accessing the stack pointer register and dereferencing it with some compiler-decided offsets that refer to the storage of each particular variable.
Here’s an example. This simple function:
When compiled with clang and no optimizations, gives me the following output on my machine:
I added some comments to explain what each line of the generated code does. The important things to see are that there are two variables on the stack – one at
0xf8(%rbp)(orrbp-8to be clearer) and one at0xfc(%rbp)(orrbp-4). The basic algorithm is just like the original code shows – the constant5gets saved intoxatrbp-4, then that value gets copied over intoyatrbp-8.“But where does the stack come from?” you might ask. The answer to that question is operating system and compiler dependent, though. It’s all set up prior to your program’s
mainfunction being called, at the same time as other runtime setup required by your operating system takes place.