473,382 Members | 1,809 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

About Stack

#include <iostream.h>
#include <string.h>

char *fun(void);

void main()
{

char *p = fun();

cou<<p;

}

char *fun()
{

char buf[32];
strcpy(buf,"hello");
return buf;
}

In this program how the address of the buffer will be pass to the pointer?
I am confused caz buf is a local variable, and when fun() come back to the main at that time if I am not wrong stack will be cleared.
Can I know the stack working for main and for the function fun()?
or from where can i get the information about the stack?
Oct 1 '06 #1
4 2079
Banfa
9,065 Expert Mod 8TB
Expand|Select|Wrap|Line Numbers
  1. char *fun()
  2. {
  3.   char buf[32];
  4.   strcpy(buf,"hello");
  5.   return buf;
  6. }
  7.  
This is an error and very very poor style. You should not return a pointer to a local variable because as soon as you return that pointer is no longer valid as the memory for the variable is returned to the stack. This invokes undefined behaviour.

If you continue to do this in the end you will cause bizzare and hard to trace errors in your program.

You should either make the variable returned static, but then there will only ever be 1 copy of the variable so each call will overwrite the previous data.

Expand|Select|Wrap|Line Numbers
  1. char *fun()
  2. {
  3.   static char buf[32];
  4.   strcpy(buf,"hello");
  5.   return buf;
  6. }
  7.  
or allocate the memory for the pointer but then the calling code must free the memory or cause a memory leak


Expand|Select|Wrap|Line Numbers
  1. char *fun()
  2. {
  3.   char * buf;
  4.   buf = malloc(strlen("hello")+1);
  5.   if (buf != NULL)
  6.   {
  7.     strcpy(buf,"hello");
  8.   }
  9.   return buf;
  10. }
  11.  
Or return a pointer to a string constant but then you can not alter the data returned


Expand|Select|Wrap|Line Numbers
  1. const char *fun()
  2. {
  3.   return "hello";
  4. }
  5.  
Oct 1 '06 #2
ya though buf is a local variable. my output is correct.
that is why i am not getting the point, how my output is correct.
I am using Turboc++ compiler
Oct 1 '06 #3
D_C
293 100+
Once you exit the function fun(), the memory occupied by buf no longer belongs to your program. It is possible, yet not probable, that some other program requests memory and it gets the memory that buf occupied.

The memory now belongs to that program, and it can change the contents of buf to whatever it wants and it has every right to do so. Then, when you access the memory that now belongs to the other program, you may print something other than "hello".
Oct 2 '06 #4
Banfa
9,065 Expert Mod 8TB
Indeed, just because your code no longer owns the memory doesn't mean that it has been overwritten, it just means that it shouldn't be accessing it.

On my system I do not get "hello" output at all because ostream& ostream::operator<<(const char * s) puts data on the stack.

However try this

Expand|Select|Wrap|Line Numbers
  1. #include <iostream.h>
  2. #include <string.h>
  3.  
  4. char *fun(void);
  5.  
  6. void main()
  7. {
  8.  
  9.     char *p = fun();
  10.  
  11.     NotFun();
  12.  
  13.     cout<<p;
  14. }
  15.  
  16. char *fun()
  17. {
  18.  
  19.     char buf[32];
  20.     strcpy(buf,"hello");
  21.  
  22.     return buf;
  23. }
  24.  
  25. void NotFun()
  26. {
  27.  
  28.     char buf[32] = "I'm having a bad day, go away";
  29. }
  30.  
Oct 2 '06 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

45
by: Edward K. Ream | last post by:
Hello all, First of all, my present state of mind re pep 318 is one of sheepish confusion. I suspect pep 318 will not affect Leo significantly, but I am most surprised that an apparently...
7
by: Aguilar, James | last post by:
Hello all, To begin, yes, this -is- a homework assignment. However, it is for my Algorithms class, and my instructor has given us explicit permission to use "expert" groups like newsgroups, so...
5
by: Tony Johansson | last post by:
Hello experts! I have two class template below with names Array and CheckedArray. The class template CheckedArray is derived from the class template Array which is the base class This program...
20
by: Sushil | last post by:
Hi gurus I was reading FAQ "alloca cannot be written portably, and is difficult to implement on machines without a conventional stack." I understand that the standard does not mandate...
13
by: gmccallum | last post by:
General Info: A struct is stored on the stack and a class on the heap. A struct is a value type while a class is a reference type. Question: What if a struct contains a string...
53
by: jaso | last post by:
Can you give any comments on this code? I used one goto, is it bad? #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <assert.h> #define NOT_NULL 1
15
by: rover8898 | last post by:
Hello all, I used setjmp() in a recent of program of mine (it is not completed, so I have not the chance to test it out yet). I am not very profocient in C coding as are some of my co-workers....
75
by: Steven T. Hatton | last post by:
No, this is not a troll, and I am not promoting Java, C-flat, D, APL, Bash, Mathematica, SML, or LISP. A college teacher recently posted to this newsgroup regarding her observation that there has...
25
by: Haskell Prelude | last post by:
Hello Friends - Can anyone answer these C questions? 1. Given the following initial declarations and value assignments: int ints = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130,...
14
AmberJain
by: AmberJain | last post by:
Hello, I am presently studying Data structures in C. And so I have a simple question about stack. The book which I got my hands on says about stack: For me this quote (from the book) is a bit...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.