• C

conceptual pointers question

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
LVL 16
manav_mathurAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

cjjcliffordCommented:
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
manav_mathurAuthor Commented:
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
manav_mathurAuthor Commented:
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
Prepare for an Exciting Career in Cybersecurity

Help prevent cyber-threats and provide solutions to safeguard our global digital economy. Earn your MS in Cybersecurity. WGU’s MSCSIA degree program curriculum features two internationally recognized certifications from the EC-Council at no additional time or cost.

grg99Commented:
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
cjjcliffordCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
cjjcliffordCommented:
grg99, I love that analogy!!!
0
grg99Commented:
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
Kent OlsenData Warehouse Architect / DBACommented:

Hi grg99,

Your mainframe background is showing.  :)

Which leads to the old CDC joke about the difference between a CPU and a PPU .....
0
grg99Commented:
>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
Kent OlsenData Warehouse Architect / DBACommented:

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
grg99Commented:
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
Kent OlsenData Warehouse Architect / DBACommented:

"Two C's", I can surmise.  K?
0
grg99Commented:
> "Two C's", I can surmise.  K?

  K = Kitchen

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


0
Kent OlsenData Warehouse Architect / DBACommented:

'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
SaMuElCommented:
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
Kent OlsenData Warehouse Architect / DBACommented:
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
SaMuElCommented:
lol, yes, I can see a vague simalarity :D
Thanks for pointing that out Kdo
0
grg99Commented:
Please note this isnt totally thread-safe:

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

0
cjjcliffordCommented:
grg99, why not?  "a" is a local variable...
0
manav_mathurAuthor Commented:
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
grg99Commented:
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
Kent OlsenData Warehouse Architect / DBACommented:

>> 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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.