/////////////// code 1 start ///////////////////////
char *GetString(void )
{
char p[] = "hello world";
return p;
}
void Test4(void)
{
char *str = NULL;
str = GetString();
cout<< str << endl;
}
/////////////// code 1 end ////////////////////////
///////////////// code 2 start ////////////////////
char *GetString2(voi d)
{
char *p = "hello world";
return p;
}
void Test5(void)
{
char *str = NULL;
str = GetString2();
cout<< str << endl;
}
///////////////// code 2 end /////////////////////
Q: What is the difference between code 1 and code 2? 10 1532
zhou xiang wrote: /////////////// code 1 start /////////////////////// char *GetString(void ) { char p[] = "hello world"; return p; } void Test4(void) { char *str = NULL; str = GetString(); cout<< str << endl; } /////////////// code 1 end ////////////////////////
///////////////// code 2 start //////////////////// char *GetString2(voi d) { char *p = "hello world"; return p; } void Test5(void) { char *str = NULL; str = GetString2(); cout<< str << endl; } ///////////////// code 2 end /////////////////////
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.
"zhou xiang" <ju********@eyo u.com> skrev i en meddelelse
news:82******** *************** ***@posting.goo gle.com... /////////////// code 1 start /////////////////////// char *GetString(void ) { char p[] = "hello world";
Here you declare a local array and initialise it to "Hello world".
return p;
.... and you return a pointer to that array, and deallocate it - thus p will
likely point to garbage. } void Test4(void) { char *str = NULL; str = GetString(); cout<< str << endl;
This is undefined behaviour and might print garbage or stop the program.
} /////////////// code 1 end ////////////////////////
///////////////// code 2 start //////////////////// char *GetString2(voi d) { char *p = "hello world";
Here you declare a pointer which points to a constant static area containing
"hello world". This is okay, but dangerous: the area could be changed (e.g.
by executing p[0] = 'H'), but that would lead to undefined behaviour.
The above line should read
char const* p= ...;
return p; } void Test5(void) { char *str = NULL; str = GetString2(); cout<< str << endl; }
/Peter
Andrey wrote: the second is fine since you dynamically allocate memory in the heap.
In how far is 'char * p = "hallo";' dynamic memory allocation?
The pointer p will point to nothing as well when leaving the scope.
Am I missing something?
Regards,
Matthias
Andrey <st*******@yaho o.ca> wrote in message news:<rzgod.296 877$Pl.79890@pd 7tw1no>... 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
Matthias Käppler wrote: Andrey wrote:
the second is fine since you dynamically allocate memory in the heap.
In how far is 'char * p = "hallo";' dynamic memory allocation? The pointer p will point to nothing as well when leaving the scope.
Am I missing something?
Regards, Matthias
I think you are right. no memory allocation was done. It doesn't work
even in the scope of the function.
I thougt there was new, I missed that. mistake.
Regards, Andrey
Andrey wrote: Matthias Käppler wrote:
Andrey wrote:
the second is fine since you dynamically allocate memory in the heap. In how far is 'char * p = "hallo";' dynamic memory allocation? The pointer p will point to nothing as well when leaving the scope.
Am I missing something?
Regards, Matthias
I think actually it would be good (in some sence) if you could write
like this:) But you always have to mess with char arrays allocating and
freeing memory for them. Ceratinly you should know how to do it but
that's annoying. That's why I like CString from MFC library, well
written class(template) , though I'm not thinking too well about the rest
of MFC. It'd be good to have an implementation of CString away from MFC
library. There're some alternatives certainly, but are there which are
as good as CString?
Andrey.
Original code once again:
char *GetString2(voi d)
{
char *p = "hello world";
return p;
}
"Matthias Käppler" <no****@digital raid.com> wrote in message
news:cn******** *****@news.t-online.com... Andrey wrote:
the second is fine since you dynamically allocate memory in the heap. In how far is 'char * p = "hallo";' dynamic memory allocation?
You are right, no dynamic memory allocation above.
The pointer p will point to nothing as well when leaving the scope.
This is not correct though. The string literal "hello world" has static
duration and will be valid for the lifetime of the program.
p above points to that static storage, GetString2 returns a copy of p, still
pointing to that static storage. The callers of GetString2 can access the
returned pointer.
There is another point to be made though: The code better be written to use
'char const *' types. Because the string literal is actually constant:
char const * GetString2(void )
{
char const * p = "hello world";
return p;
}
The previous definition would make some compilers compile the code but cause
undefined behavior at runtime if in fact some caller tries to modify the
content:
char * returned = GetString2();
returned[0] = 'a'; // undefined behavior
If the function were written with 'char const *', the compiler would not
allow this code.
Ali
Andrey wrote: I think actually it would be good (in some sence) if you could write like this:) But you always have to mess with char arrays allocating and freeing memory for them. Ceratinly you should know how to do it but that's annoying. That's why I like CString from MFC library, well written class(template) , though I'm not thinking too well about the rest of MFC. It'd be good to have an implementation of CString away from MFC library. There're some alternatives certainly, but are there which are as good as CString?
Andrey.
std::string? ^^
It's the string class from the C++ standard library. It doesn't have a
printf-like operation like CString's Format(), but apart from that it has
all the desired operations like operator+= for concatenation and so on.
I almost -never- use C-style strings. Too error prone. Too unhandy.
Regards,
Matthias
> /////////////// code 1 start /////////////////////// char *GetString(void )
void in the parameter list is redundant and considered bad style.
{ char p[] = "hello world";
That's a local variable which will be destroyed...
return p;
....here. Therefore, the address returned is invalid.
} void Test4(void) { char *str = NULL; str = GetString();
str points nowhere.
cout<< str << endl;
oops.
} /////////////// code 1 end ////////////////////////
///////////////// code 2 start //////////////////// char *GetString2(voi d)
idem.
{ char *p = "hello world";
That should be
const char *p = "hello world";
This is different. The string is place somewhere in outer-space where
all things are const. IIRC, the string is guaranteed to exist for the
whole program. What I am sure of is that the string cannot be modified
(and your program will crash if you try to). Therefore, if you don't
touch that string, the program will run as expected.
Jonathan This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: lawrence |
last post by:
I've been bad about documentation so far but I'm going to try to be
better. I've mostly worked alone so I'm the only one, so far, who's
suffered from my bad habits. But I'd like other programmers to have an
easier time understanding what I do. Therefore this weekend I'm going
to spend 3 days just writing comments. Before I do it, I thought I'd
ask other programmers what information they find useful.
Below is a typical class I've...
|
by: Dmitry D |
last post by:
Hi,
I'm new to C++ (started learning in the beginning of this summer), and I
have the following question (sorry if it sounds stupid):
In many code samples and source files, I see NULL expression being used (for
example, int* someInt=NULL; ). I used similar initialization myself, and it
works fine even if I don't define NULL. But what is "NULL" exactly? Is it a
constant defined by compiler? Is there any difference between the following
two...
|
by: wongjoekmeu |
last post by:
Hello All,
I am learning C++ at the moment. Going through the book of SAM of
learning C++ in 21 days I have learned about pointers that it is good
custome to always initialise them and to use delete before you try to
give it a new address.
Can anyone explain to me why this code below which seems to voilate
this rule works ?
-------------------
int main()
|
by: Rano |
last post by:
/*
Hello,
I've got some troubles with a stupid program...
In fact, I just start with the C language and sometime
I don't understand how I really have to use malloc.
I've readden the FAQ http://www.eskimo.com/~scs/C-faq/faq.html
but it doesn't seem to answer my questions...
So, I've made an example behind, with some included questions...
|
by: sunglo |
last post by:
My doubt comes from trying to understand how thread return values work
(I know, it's off topic here), and I'm wondering about the meaning of
the "void **" parameter that pthread_join expects (I think this is
topical, since it's a C question, but please correct me and apologies
if I'm wrong).
I suppose that it's this way to allow for "generic" pointer
modification, but this implies dereferencing the "void **" pointer to
get a "void *"...
| |
by: Yuri_Юрий |
last post by:
I'm confused about the VARIABLE LENGTH ARRAYS.
{scanf("%d",&n);float a;}
In which compiler can I use it?
I tried VC++6.0 SP6,but it's reported error:CONSTANT EXPRESSION!
Another question,
What the differences between:
(1)ElemType array
(2)array=(ElemType*)malloc(N*size of(ElemType))
or array=(ElemType*)calloc(N,size of(ElemType))
|
by: key9 |
last post by:
Hi All
On coding , I think I need some basic help about how to write member
function .
I've readed the FAQ, but I am still confuse about it when coding(reference /
pointer /instance) , so I think I need some "template".
Sorry for my coding experience in c++
|
by: James Dow Allen |
last post by:
The gcc compiler treats malloc() specially! I have no
particular question, but it might be fun to hear from
anyone who knows about gcc's special behavior.
Some may find this post interesting; some may find it
off-topic or confusing. Disclaimers at end.
The code samples are intended to be nearly minimal
demonstrations. They are *not* related to any
actual application code.
|
by: Deep |
last post by:
I'm in doubt about what is smart pointer. so, please give me simple
description about smart pointer and an example of that. I'm just
novice in c++.
regards,
John.
|
by: DiAvOl |
last post by:
Hello everyone, merry christmas!
I have some questions about the following program:
arrtest.c
------------
#include <stdio.h>
int main(int agc, char *argv) {
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |