Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'd like to know why local variables do not get recreated if the function is recalled?
#include <iostream>
using namespace std;
void func(void)
{
int a = 0;
cout << &a << endl;
}
int main(void)
{
func();
func();
func();
func();
system("pause");
return 0;
}
Why is the variable a mapped every single time to the same memory address?
The address of a local variable is not defined by the standard. It may be the same from one call to the next, or it may be different.
In this particular case, with this code and on your machine and compiler, the address is most likely the same because each time func is called it is called from main, so the stack is laid out the same each time. If you were to call some other function from main and then call func, the address would most likely be different.
This behavior cannot be depended on, however.
The variable is recreated every time, but the same address is reused becauseā¦ well, because why not? Every time, it is an available memory location with nothing else in it. Why not use it? If you required a different location each time, you'd eventually "run out" of memory for no reason. It's convenient for your system to re-use the same location for the same variable in the same function. If your program were more complex, you'd be likely to see less predictable behaviour, though.
You've demonstrated that stack variables may be at the same address when you call a function when the stack is in the same state.
Why not try calling the function when the stack is in a different state? For example, make it recursive:
#include <iostream>
using namespace std;
void func(int n)
{
int a = 0;
cout << "n=" << n << ": " << &a << endl;
if (0 < n)
func(n-1);
}
int main()
{
func(5);
return 0;
}
Example output:
n=5: 0x7fff519aa848
n=4: 0x7fff519aa808
n=3: 0x7fff519aa7c8
n=2: 0x7fff519aa788
n=1: 0x7fff519aa748
n=0: 0x7fff519aa708
As you can see, each call to func() has the stack in a different state, therefore the address of a can be different each time.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
Improve this question
After reading this answer I decided to try it. To my surprise, the following code is working, and the reference is correctly reseated. Why's that?
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 1;
int& ref{a};
ref = b;
cout << ref << endl;
return 0;
}
The reference ref itself was not reset. It still references the variable a. This statement
ref = b;
changed the value of the referenced variable a. To be sure insert this statement
std::cout << "a = " << a << '\n';
You can consider references as an aliases for variables they refer.
A reference is just an alias to the variable it refers to. Once a reference has been bound, it cannot be rebound. Anything you do to a reference afterwards actually happens instead to the variable it refers to. If you read from a reference, it reads from the variable instead. If you assign a value to a reference, it assigns the value to the variable instead. If you take the address of a reference, it takes the address of the variable instead.
So, these statements:
ref = b;
cout << ref << endl;
are really just doing this instead:
a = b;
cout << a << endl;
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm playing around with the Sleep() function in C++ right now, and I am not understanding why this code operates the way it does.
I made a program to find the difference between two times, but it is not working as expected.
#include <iostream>
#include <chrono>
#include <Windows.h>
using namespace std;
int main() {
int timeA = (int)chrono::system_clock::now;
cout << timeA << "\n";
for (int i = 0; i < 5; i++) Sleep(1000);
int timeB = (int)chrono::system_clock::now;
cout << timeB << "\n";
int timeDifference = timeB - timeA;
cout << timeDifference;
cin.get();
return 0;
}
It seems as if the program is setting the variables at the same time, and then sleeping. Is this the case? If so, help me to understand why, please.
now is a function, not an attribute or variable. You failed to call it, and are casting the function pointer itself to int, which will always produce the same value for a given run (on a typical 64 bit system, the low 32 bits of the address where now is located).
Change both lines to use chrono::system_clock::now(), not chrono::system_clock::now.
Note that this is one of the reasons to avoid C-style casts, as well as a reason to compile with warnings turned up; it protects you from casting to wildly incorrect end results, without at least some sort of alert.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int b;
printf("hello");
for(b=1;b<=100;++b)
{
if(b%10==1){
cout << "\n";
for(int l=0;l<=100;++l)
cout << "-" ;
cout << endl;
}
printf("|%s|",b);
}
return 0;
}
enter image description here
printf which is placed outside of loop body works fine but the one placed in the loop body of for causes some kind of error while running!! take a look at the picture !
Your b is an int.
You give b where printf() expects a pointer to char and will attempt to dereference the value you give as such.
Since the value you give via b is not a valid pointer to anything, your program has some access problem.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i am declaring a constant (a large structure constant containing string) inside a function and it is used only inside this function.
will it have any execution time impact on my program? '
They will be created every time the function is called (take more time) or only once and the reference will be used through out its life.
If i declare the constant outside the function (global) will it be faster in execution ?
Actually, declaring variables inside of a function is a great practice. If that variable is only to be used inside of that function of course. There won't be any performance differences between the two methods, but making the constant global may require a more creative naming scheme while the one inside the function can be generic. It is only being used inside of that function, after all.
static struct can help you setting it up once and be done with it. This will be coming from data segment and initialise during at the startup. A raw and dirty code below, but will give you some intuition.
#include <stdio.h>
struct A {
int a;
int b;
};
void func(void)
{
static struct A a = {5,3};
printf("FUNC: A.a: %d\n", a.a);
}
int main(int argc, char **argv)
{
static struct A a = {6,4};
printf("MAIN: A.a: %d\n", a.a);
func();
return 0;
}
I would personally move it out of the function body if any other related functions use the variable, as long as you're using namespaces.
Also if its a true constant, I believe you can declare a struct static constexpr, which means that it won't be allocated on the stack every time the function is called (static), even if you declare it inside the function body. It also means that where it can be used at compile time, it will be (constexpr).
#include <iostream>
namespace Test{
struct Test {
char name[11];
int a;
int b;
};
static constexpr Test TEST_CONSTEXPR = {
"test value",
5,
6
};
}
int main()
{
std::cout << Test::TEST_CONSTEXPR.name << std::endl;
std::cin.get();
return 0;
}
In Ada this is compiler dependent. (As performance usually is.)
As "constants" are not compile-time static, a compiler may do the safe thing and evaluate the initialising expression every time the constant is declared.
If it really matters, measure what your compiler does.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am new to c++, but not to OOP. This crash confuses me so much.
This is a piece of my main. This code works. It prints what I want it to print.
int _tmain(int argc, _TCHAR* argv[]) {
Weapon* wp = createWeapon();
cout <<wp->name << " " << wp->maxAttack << " " << wp->minAttack; //<<---Works fine
}
But. The following code, only passing it through a function to do the same thing, crashes. And I have no idea why. I have tryed anything I could think of, but upon entering the new function, something changes the data and it crashes.
void showWeaponInfo(Weapon* w) {
cout << "Weapon: " << w->name << "\n"; //Wont work!??!
}
int _tmain(int argc, _TCHAR* argv[]) {
Weapon* wp = createWeapon();
showWeaponInfo(wp);
}
I have debugged, and that shows that upon entering the new function, the data in "wp" changes. The following links are images of the debugging.
Am I doing something wrong? Has someone else encountered this problem? Do you have to think of something special when passing pointers as arguments?
In VC++ the debugger sets the values of unassigned variables to 204 per byte or as in your case - 0xCCCCCCCC
This means that your createWeapon() returns uninitialized pointer.
You don't show us your createWeapon(). But I guess the createWeapon() returns the pointer of local variable. Is your function like this?
Weapon* createWeapon()
{
Weapon wp(/*blabla*/);
// ...
return ℘
}
If so, you've encountered undefined behavior.
On the end of createWeapon(), the wp variable, local variable of createWeapon(), is destroyed. Therefore, the returned pointer points to "destroyed" object. If you try to dereference that pointer, the program falls in undefined behavior, which means nobody knows what would be happened.
However, directly after calling createWeapon(), the wp variable might be alive - since the stack frame is not touched yet. That's why your first example seems to work. But in your second example, you call showWeaponInfo(), and the calling change the stack frame.