Not getting right Output of Character Array [duplicate] - c++

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.

Related

When I run this code, result is always 24 regardless of what string is. Why? [duplicate]

This question already has answers here:
c++ sizeof( string )
(9 answers)
Closed 1 year ago.
When I run this code, result is always 24 regardless of what string is. Why?
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s = "asdccccc";
cout << sizeof(s);
return 0;
}
A string is an object. By using sizeof you are getting the size of the members of that object. One of those members is probably a pointer to the actual string contents, but the size of a pointer is constant no matter what it points to.
Consider this simple example
class string
{
const char* _ptr;
....
....
public:
}
When you write sizeof(string), you will get the size of the class, not the size of string literal _ptr points to.

In char **function() , dynamic allocation of char array gives undesired result [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
This is my C++ code .
According to me , it should give output:
abc
Garbage
abc
But it is giving output:
abc
Garbage
Garbage
#include<bits/stdc++.h>
using namespace std;
char **func()
{
char* PA = new char[10];
PA[0]='a';
PA[1]='b';
PA[2]='c';
PA[3]='\0';
printf("%s\n",PA);
printf("Garbage\n");
char **PPA = &PA;
return PPA;
}
int main()
{
printf("%s\n",*func());
return 0;
}
Where am I doing wrong?
char **PPA = &PA;
Retrieves the address of the variable PA itsself, which is an automatic variable and goes out of scope as soon as the function terminates. That means you have undefined behavior here. The C standard doesn't guarantee any consistent behavior, so anything may happen, including what you experienced.
To fix that, you could change the function prototype to char* func() and return PA directly and remove PPA altogether.

Not using static string variable [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
Is there another efficient way to write code below not using static string variable? The reason is that, I use the code below to illustrate the crash happening in a bigger project that uses this static string variable. But if I remove the static keyword, the code will not crash, but the contents of string variable are nothing.
std::string conversation;
const char *GetFoo()
{
static std::string word;
word ="hello ";
word +="buddy.";
word +=" How are things?";
return word.c_str();
}
void CallGetFoo()
{
const char *pp = GetFoo();
conversation +=pp;
cout<<pp;
}
int _tmain(int argc, _TCHAR* argv[])
{
CallGetFoo();
return 0;
}
You're experiencing the classic issue of returning a pointer/reference to data that is local to a function. When you remove the static keyword, then the word variable is destructed at the end of the function. That means the c_str that it returns is going to be garbage and you'll end up with undefined behavior. The static keyword keeps the object around so that it will remain the same through multiple calls to the function. Like the comments say, you're better off returning a std::string.
Returning a std::string will copy the contents of the local variable to the caller's std::string. More than likely, the compiler will be able to optimize out the copy and do something called Return Value Optimization (RVO), but that is a separate topic.

Both &i and p are pointing to the same variable but showing different result? [duplicate]

This question already has answers here:
How is a variable at the same address producing 2 different values? [duplicate]
(4 answers)
Closed 8 years ago.
Both &i(inside main function) and p(inside func function) holds the same address. Well I know that a constant object/variable cannot be modified but I'm able to increment the variable i using (*p)++ in the func function, but the result is not reflecting in the main function. Why is that?
#include <iostream>
using namespace std;
void func(int *p){
(*p)++;
printf("%p %d\n", p, *p);
}
int main(int argc, char **argv){
const int i = 47;
const int *p = &i;
func(const_cast<int *>(p));
printf("%p %d\n", &i, i);
return 0;
}
I'm getting this output:
000000000022fe44 48
000000000022fe44 47
Because of undefined behavior. You are modifying constant data. That const_cast should be a big hint.
Object declared const at point of it's definition is truly a const object. That mean results of modifying that object is undefined.
Undefined means it's totally upto the compiler what it wants to do with your code. In your case, it seems compiler allocated that truly const in read only memory. When you passed this to function taking non-const pointer, compiler might have provided that function with another memory containing similar value. But that's just my speculation.
EDITED in response to comment by #FreeNickName:-
Since addresses of both pointers ( one in main and other in func )are same, I think above is not giving correct/complete picture what's going on under the hood. Maybe compiler is just ignoring that increment instruction as it is being applied on memory that's read only.

Functions that return const char* [duplicate]

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.