Passing pointer to function changes data and crashes program [closed] - c++

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 &wp;
}
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.

Related

How does pointer in function work at this code? [closed]

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 6 years ago.
Improve this question
int f_point(int kek,int *lol) {
*lol *= *lol;
return kek;
}
int main {
int x;
std::cin >> x;
int *adress_of_x = &x;
int a,b = f_point(x,&x); //how does it work?
std::cout << a << LINE_JUMP;
std::cout << b << LINE_JUMP;
}
For example, if I give 2 to program then I will get 0 and 2. Why?
b = f_point(x,&x) in this statement value of first parameter is 2.
Your function is not changing the value of first parameter and returns the same value.
Your are passing first parameter by value so it has no relation with the updated value of x. Variable a is uninitialized, so it is taking a garbage value.
int a,b = f_point(x,&x); //how does it work?
The variable declaration leaves a uninitialized and initializes b from the result of f_point(x,&x);.
Since it's an uninitialized variable, accessing the value of a in the
std::cout << a << LINE_JUMP;
statement leads to undefined behavior of your program. Having an output of 0 is just one of any possibilities (including your fridge explodes unexpectedly or little demons flying out of your nostrils).

Local variables - recreated [closed]

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.

C++ scopes and allocation [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 6 years ago.
If I understand correctly, variables that are not dynamically allocated are supposed to be deleted at the end of their scope.
However, I wanted to try it out with this code (which I think is not correct as I am supposed to use dynamic allocation) :
int* function()
{
int a = 3;
return &a;
}
int main(int argc, char const *argv[]) {
int* a(function());
std::cout << *a << std::endl; // prints 3
}
Why can I still access the value of the variable a by using the pointer returned by the function when it is supposed not to exist anymore ?
a and hence the return value from function has gone out of scope. You are just lucky.
Just be careful and compile with all the warnings enables - and take heed of those warnings.
The fact that you can access the value is pure luck. The code has undefined behaviour (since the variable is destroyed) and the compiler can generate whatever it wants - but you cannot rely on it.

C++ Stack vs Heap and Pointers [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
So I'm learning C++ (coming from a Java background). I thought I understood how memory works on a high level (stack vs heap and pointers). To experiment, I wrote the following two toy functions:
int* pntrToHeap(int val) {
return new int(val);
}
and
int* pntrToStack(int val) {
return &val;
}
At first I thought pntrToStack just wouldn't work, because the local variable val is on the stack which is "deleted" after the function exits. But after the following code worked without errors (with 1 warning, however), I reconsidered:
int main()
{
int val1 = *pntrToHeap(3);
int val2 = *pntrToStack(4);
cout << val1 << endl;
cout << val2 << endl;
return 0;
}
Both 3 and 4 printed to the screen. It seems as though the stack isn't actually deleted, but the CPU just loses the ability to access local variables on it -- is this correct? If so, in a case like this, which function should we prefer?
Lastly, since val1 is a local variable of main, is pntToHeap creating a memory leak since I can't delete the value it created on the heap?
I know these concepts have been asked about before, but I couldn't quite find the answers. Thanks!
Definitely the first one! If you want something to live after the stack frame expires you should heap allocate it.
And yes, the value pointed to by the pointer returned from pntrToStack will be overwritten the next time you allocate a new stack frame ie. call a function. When you exit out of a scope the memory is not erased. It is merely marked as being free to allocate.

array of pointers in C++ and what is "BUS ERROR" [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main()
{
int a[]={0,1,2,3};
int *r[]={NULL};
for(int i=0;i<4;i++)
{
r[i]=&a[i];
cout << &a[i] << endl;
cout << a[i]<<endl;
}
for(int i=0;i<4;i++)
{
cout << r[i] << endl;
cout << *r[i] << endl;
}
return 0;
}
I have started working on the array of pointers very recently. Can someone please help me out in finding the mistake in the above program..
I attached the screenshots of the results when run on windows and linux platforms.
On Windows,the addresses of the *r[] and a[] are matching and still the values are not matching.
On linux,it says "BUS ERROR" sometimes and "Segmentation fault" sometimes.
It would be better if someone explain what the "BUS ERROR" mean? And why does it come for this program.
Your array r only has space for a single element in it, but you store 4. That overwrites memory, causing the crash.
Change this:
int *r[]={NULL};
to:
int *r[sizeof a / sizeof *a];
This makes r have the same number of elements as a, in other words 4.
int *r[]={NULL}; should be int *r[]={0, 0, 0, 0};
That will allocates space for four pointers that your following code need.
BUS ERROR: What is a bus error?
Your are not allocating enough space for your r. Try int *r[4]; and you will not get a segmentation fault.
int *r[] = {0} it's equivalent with int *r[1];
r is an array of pointers, but in your code, it has only one element. You are lucky to run it on windows but it's a undefined behavior. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems that is going to cause yet.