?
Solved

conceptual pointers question

Posted on 2004-11-03
22
Medium Priority
?
264 Views
Last Modified: 2010-04-15
Hi,

excuse me if Im missing something here.....
but

char* retstring()
{
    char a[] = "Somestring" ;
    return a;
}
void main
{
    char* p=retstring() ;
    cout<< p;
}

prints garbage in my C++ compiler.

Please explain
Manav
0
Comment
Question by:manav_mathur
  • 7
  • 6
  • 4
  • +2
22 Comments
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12484849
the local variable "char a[]" is created on the stack, and shouldn't be returned like this (G++/GCC warns about this...) since the contents of the stack could be changed between your call and the use (which is obvious in your example, as garbage is being output!)
If you must do something like this, use strdup() for the return string (not good, an easy source of memory leaks), or better yet pass in an char array (and length) and use strncpy() to fill the array (to the specified length) to get the string out....
0
 
LVL 16

Author Comment

by:manav_mathur
ID: 12484896
cjjclifford,
Can you please explain in a bit more detail. AFAIK, the compliler takes care of segregation of program stacks and data stacks. i.e, the function stack would be seperate from the data stack......

>contents of the stack could be changed between your call and the use
Can you give an example scenario so that it makes it clear??

Manav
0
 
LVL 16

Author Comment

by:manav_mathur
ID: 12484912
cjjclifford,
Please explain in as much detail as you can, because I wont be able to access this site for 10 hours now........(have to go to sleep)

Manav
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 22

Expert Comment

by:grg99
ID: 12485108
The local variable "a" is given memory space on function entry, and that space is reclaimed at function exit.   You're passing back the address of "a" to a place AFTER "a"'s space has been returned to the stack.  Outside of the function, that address is no longer of any use.

It's like going to a whorehouse, requesting Alice, using Alice, writing down her social security number on a piece of paper, releasing Alice, then going back home with the number.   Once you're home you can't use that SSN as a substitute for Alice.   :)

Hope this clears things up.



0
 
LVL 11

Accepted Solution

by:
cjjclifford earned 200 total points
ID: 12485124
10 hours sleep???? luxury!

the variable you create inside the function is placed onto the stack. when the function returns and another function is called the same area of stack will be re-used. You are returning a pointer, which is just a memory address, in this case the memory address of the area of stack used inside the function.. since the function has returned, the memory being pointed to should be considered invalid, since it will be re-used again for other functions' local variable space...
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12485126
grg99, I love that analogy!!!
0
 
LVL 22

Expert Comment

by:grg99
ID: 12485202
A better analogy, you go there, the front desk says "You''re all set to use Alice in Room 3749", you do your business with Alice, then you exit the establishment.  

Once out of the place, you can't use the number "3749" for anything anywhere near as much fun (Obligatory PC note: or as DIsgusting, Expoitative, and just plain Jerky).

0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 12486463

Hi grg99,

Your mainframe background is showing.  :)

Which leads to the old CDC joke about the difference between a CPU and a PPU .....
0
 
LVL 22

Expert Comment

by:grg99
ID: 12486543
>Which leads to the old CDC joke about the difference between a CPU and a PPU .....
Never heard that joke.   What's the punchline? :)

The only CDC tie I can see is if one told a joke that was in any way racy, people would say "Watch Out, 88", which was the number of the page in the company rule book about "Sexual Harrassment".

Oh, now I remember another CDC joke.  During the Crash of 1970, lots of people got the axe.  This black humor went around.
Manager calls in a female employee:  "I'm going to have to lay you or Jack off". "Well, you're not going to lay me, so ...."

 
0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 12486670

Page 88, huh?  I don't have a company rule book anymore, but I do still have an old CDCNET directory.  :)

Well unfortunately, the punchline contains a couple of key words that I can't put in this forum.  :(

Sunny doesn't know any way for me to give up the punchline without getting banned from the site.

SIDKE,
Kent
0
 
LVL 22

Expert Comment

by:grg99
ID: 12486826
Okay, that's a big enough hint.

Just read Augesten Burroughs book, and learned the advertising term for a dishwashing liquid commercial:

"Two C's in a K"

0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 12487049

"Two C's", I can surmise.  K?
0
 
LVL 22

Expert Comment

by:grg99
ID: 12487760
> "Two C's", I can surmise.  K?

  K = Kitchen

You may have to re-evaluate C given that bit of info.


0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 12487806

'Kitchen' was all that I could come up with, but I can't make much sense of the expression.  I'm assuming that C is the same as the C in CPU in the joke above, which means that the expression could be used for any kitchen product.


0
 
LVL 2

Expert Comment

by:SaMuEl
ID: 12489019
char* retstring()
{
  char a[] = "Somestring" ;
  char *b;
  b=malloc(sizeof(char)*strlen(a)+1);
  strcpy(b,a);
  return b;
}
void main()
{
  char* p=retstring() ;
  printf("%s",p);
}

Otherwise better to write a function to take a pointer as argument retstring(char*);
0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 12489112
Hi SaMuEl,

>char* retstring()
>{
>  char a[] = "Somestring" ;
>  char *b;
>  b=malloc(sizeof(char)*strlen(a)+1);
>  strcpy(b,a);
>  return b;
>}

Is this anything like:

char * strdup (const char* source);


:)

0
 
LVL 2

Expert Comment

by:SaMuEl
ID: 12490609
lol, yes, I can see a vague simalarity :D
Thanks for pointing that out Kdo
0
 
LVL 22

Expert Comment

by:grg99
ID: 12493445
Please note this isnt totally thread-safe:

>  b=malloc(sizeof(char)*strlen(a)+1);
>  strcpy(b,a);

0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12493473
grg99, why not?  "a" is a local variable...
0
 
LVL 16

Author Comment

by:manav_mathur
ID: 12493499
Despite grg99's analogy :) , I think cjjclifford has explained the scenario in his third mail itself.
KDo, samuel...thanx for the alternative solution.

DO I close this and accept cjjclifford's answer or somebody else still has to say a thing or two about the "topic in discussion" :) ??

Manav
0
 
LVL 22

Expert Comment

by:grg99
ID: 12493723
grg99, why not?  "a" is a local variable...

Well, there's the obvious: it's not checking for NULL return from malloc().

And you're right, but people don't easily see the subtle requirement that "a" HAS to be local AND non-volatile AND never overriden by some #define or template AND somehow protected from access from other threads and processes and hardware.

One careless cut and paste and you have a hidden time bomb in your code.

I generally like to wear a belt AND suspenders, just my personal quirk.



0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 12494063

>> I generally like to wear a belt AND suspenders, just my personal quirk.

A good argument was made against such redundancy in "Once Upon a Time in the West".  :)

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Suggested Courses

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question