Re: About c++ pointer
From: abcd (abcd_68_at_yahoo.co.uk)
Date: 11/22/04
- Next message: Andrey: "Re: About c++ pointer"
- Previous message: Matthias Käppler: "std::string::push_back vs. std::string::operator+="
- In reply to: Andrey: "Re: About c++ pointer"
- Next in thread: Cheng Mo: "Re: About c++ pointer"
- Reply: Cheng Mo: "Re: About c++ pointer"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 22 Nov 2004 12:51:30 -0800
Andrey <stingo000@yahoo.ca> wrote in message news:<rzgod.296877$Pl.79890@pd7tw1no>...
> zhou xiang wrote:
> [...]
> > Q: What is the difference between code 1 and code 2?
> The code 1 will not work, the pointer will be empty when it returns,
> because the object(string array) is created in stack. While the second
> is fine since you dynamically allocate memory in the heap.
Nope. In neither case is the memory allocated off the heap (I can't
see any 'new' or 'malloc'). In both cases the string is statically
allocated in read-only memory (try to change it and the program will
likely crash e.g., *p='f').
The difference between the two is that in the first listing p is an
actual array, allocated on the stack. The contents of the constant
string is copied into it. It will be destroyed as soon as the flow of
control leaves function GetString(). This means that you're returning
the address of a local (and a clever compiler issues a warning). The
second listing is fine, not because you're allocating memory off the
heap (which you're not) but because you're returning a pointer to a
statically allocated string which will be there as long as the program
runs.
HTH
Andy
- Next message: Andrey: "Re: About c++ pointer"
- Previous message: Matthias Käppler: "std::string::push_back vs. std::string::operator+="
- In reply to: Andrey: "Re: About c++ pointer"
- Next in thread: Cheng Mo: "Re: About c++ pointer"
- Reply: Cheng Mo: "Re: About c++ pointer"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|