This question already has answers here:
Do pointers to string literals remain valid after a function returns?
(4 answers)
Closed 8 years ago.
Although the following code does work, I do not know why. Please explain me.
#include <iostream>
using namespace std;
const char *f()
{
const char *p = "Hello!\n";
return p;
}
int main()
{
cout << f() << endl;
system("pause");
return 0;
}
From what I learnt, the 7 chars in f() are allocated on the stack (?), meaning that their memory will be released as soon as f() ends, however, the pointer returned by f() still points to a valid address in the application memory (meaning "Hello!" is successfully sent to the output). Why?
Same thing goes for
const int *f()
{
int i = 5;
const int *p = &i;
return p;
}
int main()
{
cout << *f() << endl;
system("pause");
return 0;
}
Can anyone shed some light on this?
What you´ve learned is correct, it´s not allowed to use local function variables
(ie. their used memory) anymore after the function ends.
If it works currently it´s nothing more than coincidence:
No other code has used this piece of memory in the meantime
for own things, so the old value is still there.
Your second code snippet causes undefined behaviour. The reason why it seems to work is, that you are lucky and the memory has not been overwritten.
However (as in the comment below mentioned) the first snippet is valid.
Related
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
void changeString(const char* &s){
std::string str(s);
str.replace(0, 5, "Howdy");
s = str.c_str();
}
int main() {
const char *s = "Hello, world!";
changeString(s);
std::cout << s << "\n";
return 0;
}
When I run this code, it prints "Howdy, world!" I would think that str gets destroyed when changeString exits. Am I missing something with the way std::string gets allocated?
Yes, str is destroyed; but the memory of the string isn't cleared; your "s" pointer point to a free but non cleared memory. Very dangerous.
It's undefined behaviour when std::cout << s tries to access the pointer, because the destructor of the local std::string in changeString has freed the memory which the pointer still points to.
Your compiler is not required to diagnose the error but can instead generate a binary which can then do whatever it wants to.
The fact that you got the desired output was just bad luck because it made you think that your code was correct. For instance, I've just compiled your code on my machine and got empty output instead. It could also have crashed, or it may have done other, unrelated things.
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 8 years ago.
Improve this question
I was practicing C++ and find this task in the web. The question in of task is "What is the wrong with this code?"
#include <iostream>
void StrIn(char *sp)
{
sp = new char[256];
sp[0] = '1';
sp[1] = '2';
sp[2] = '\0';
}
int main()
{
char *pt=0;\\ something wrong here
StrIn (pt);
std::cout << pt[1];
delete[] pt;
return 0
}
First of all. I do not understand why StrIn do not changes values of elements pt[].
Second. Why program shouts down when
char *pt=0;
and works "fine" with
char *pt;
Obviously I do not understand something but I spend 4 hours on this task and don't get any closer to solution so asking you for help.
UPD:
Why the output for
std::cout << pt;
ending with "-" symbol and shows only sevral symbols inicializated in a row?
You're passing the pointer by value, so inside the function you're actually assigning to a new pointer, not the original one.
Change the function prototype to void StrIn(char *&sp).
The equivalent for your code with an integer:
#include <iostream>
void ReadInt(int i)
{
i = 2;
}
int main()
{
int i = 0;
ReadInt (i);
std::cout << i;
return 0
}
The problem here is that your are passing a copy of i, and changing it in ReadInt does not change the int in main.
There are 2 solutions:
Solution 1
Return the changed number:
int ReadInt()
{
return 2;
}
int main()
{
int i = 0;
i = ReadInt();
std::cout << i;
return 0
}
In your case:
char* StrIn()
{
sp = new char[256];
sp[0] = '1';
sp[1] = '2';
sp[2] = '\0';
return sp;
}
int main()
{
char* pt = 0;
pt = StrIn();
std::cout << pt[1];
delete[] pt;
return 0;
}
Solution 2
Pass the reference, or memory location of your variable.
For integer:
void ReadInt(int& i) which would be called like this: ReadInt(i)
//or
void ReadInt(int* i) which would be called like this: ReadInt(&i)
In your case:
void StrIn(char*& sp) which would be called like this: StrIn(pt)
//or
void StrIn(char** sp) which would be called like this: StrIn(&pt)
To get data that a double pointer points to you need to dereference the pointer.
char* deref = *(double_pointer);
I do not understand why Str do not changes values of elements pt[].
When Str is called, the value of pt is passed to it. pt is a pointer, so the value is an **address*. You are passing an address to Str. So far, so good.
Now in Str, what happens? You take your copy of the address, call it sp and immediately replace it with a new address (the one returned by new). All subsequent code in Str only modifies what is pointed at by that new address. The original address is untouched.
Then Str returns, the copy is discarded, and what was pointed at by the copy is left in memory forever (until the program ends).
The rest of the program deals with the original address.
Why program shouts down when char *pt=0; and works "fine" with char
*pt;
It's just undefined (i.e. more or less random) behaviour in both cases. In main, you use the original address, regardless of what happens with the copy in Str. A 0 address is not valid for the [] operation, neither is using an uninitialised variable.
The only real difference is with delete[], which will work fine by doing nothing with a null pointer and yield undefined behaviour with an uninitialised variable.
Obviously i do not understand somthing but i spend 4 hours on this
task and dont get any closer to solution so asking u for help.
You are mistaking real strings with char arrays or pointers (i.e. memory addresses).
In C++, when you need strings, use the std::string class and everything will work as expected.
When you use char arrays or pointers, you need to learn a lot more about language details. Start with a good tutorial or a good book. Some hours are not enough, but some days should suffice.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
char* func()
{
const int size = 24;
char bin[size];
char *temp;
for(int i=0; i<23; i++)
bin[i] = '1';
bin[23] = '\0';
temp = bin;
return temp;
}
int main()
{
char *s;
s = func();
cout << s << endl; //prints out weird values
return 0;
}
When compiled and ran, it print random values. In the function func, I initialized a char array and tried to return it. Upon returning it and printing it in main, it prints out weird values. What is wrong? Any help would be appreciated.
char bin[size];
allocate memory on the stack, you cannot refer to that location after the function returns: "char *s" is assigned a value that refer to an invalid memory location.
You must not use pointers to freed space, like the stack of a function which has finished executing.
This Undefined Behavior means anything goes, even the proverbial demons flying out of your nose.
Your choices:
Use a caller-allocated buffer.
Use a static buffer (beware reentrancy problems and multithreading woes).
Use dynamic allocation (new, new[], malloc() and friends).
return a struct (standard container or otherwise) containing the data. Might use dynamic allocation. (Last point courtesy of Matt McNabb).
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 9 years ago.
#include <stdio.h>
int *pPointer;
void SomeFunction()
{
int nNumber;
nNumber = 25;
// make pPointer point to nNumber:
pPointer = &nNumber;
}
void main()
{
SomeFunction(); // make pPointer point to something
cout<< "Value of *pPointer: "<< *pPointer <<endl;
}
I have been told that using pointers like this is dangerous, could anyone please explain why it is dangerous and what would be the 'safe' way to write that piece of code?
will 25 always be printed out to the screen in that way? if not then why?
Using a pointer to local variable outside of the scope of the variable is always dangerous. It invokes undefined behavior.
Unsafe, because its value may be overwritten
Safe way: just
int SomeFunction()
{
int nNumber;
nNumber = 25;
return nNumber;
}
Will do fine. If your return value is large, return value optimization will save your life anyway.
25 printed? Implementation specified. Most likely not because you are in a new stack frame when the function returned.
You are talkin about wild pointers which termed to be dangerous to use because a pointer, is a memory address, and in modern computers memory is protected (only allowed to be accessed by the program that owns it)
an attempt to read or write to memorry address 0 or NULL will cause your program to crash with a memory violation error.
he best way to protect againsed this to initalise a pointer as soon as it is created.
anouther way, is to test the pointer before using it.
if (pointer == 0) {
cout << "WARNING... cant use this pointer";
}
else {
// it is okay to use this pointer
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pointer to local variable
#include <iostream>
using namespace std;
char* func();
int main() {
char* str;
str = func();
cout<<str;
return 0;
}
char* func() {
char * str;
char p[] = "priyanka is a good girl";
str = p;
cout<<str<<"\n";
return str;
}
gives the output,
priyanka is a good girl
priy
I did not understand what just happened here, why an incomplete array was given as output. I am a little new with this. Please help.
Your function func() returns a pointer to a local variable, which later causes undefined behaviour when you try to access it.
In func2() char p[] is a local variable initialized on stack. Returning a pointer to stack variable is a bad idea(and is undefined behaviour as well), and I think your string "priyanka is a good girl" got overwritten when the function returned.