473,794 Members | 2,765 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

About Stack

30 New Member
#include <iostream.h>
#include <string.h>

char *fun(void);

void main()
{

char *p = fun();

cou<<p;

}

char *fun()
{

char buf[32];
strcpy(buf,"hel lo");
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 2107
Banfa
9,065 Recognized Expert Moderator Expert
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
sanketbarot
30 New Member
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 Contributor
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 Recognized Expert Moderator Expert
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::operat or<<(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
2594
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 controversial feature is being added without a notice, say, in comp.lang.python.announce. I say sheepish, because everyone knows that one should make sure new proposals don't bite you. Still, I would have thought that there were other ways of keeping...
7
7077
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 if that's your only reason not to help, please do. Otherwise, I guess it's OK. But, just remember, I'm not asking you to do my work for me, just to point out my error. My problem is not with the algorithm itself (standard divide and conquer on...
5
2085
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 works fine but there in one thing that I'm unsure about and that is the inheritance statement. What difference is it if I have this construction class CheckedArray : public Array<T>
20
3504
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 "heap" or "stack" I'm curious to know the implemenations which dont have stack or heap.
13
2315
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 property(variable). The string would be a reference type being contained in a value type. Would this filter up and cause the stack to now be a reference type placed on the heap or would it still be on the stack with a pointer used internally to point to a...
53
3193
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
2432
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. They (my co-workers) say (with vehement ardor ;) ) that the usage of setjmp() emplyoyed in function"C" that was called from function "B" that was called from function "A" that was called form the main(), will cause havoc in the stack. And it makes...
75
5483
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 been a significant decline in the number of students opting to take courses in C++. I just want to let people know what I believe are the biggest obstacles to C++ language acquisition, and what aspects of the language make it less appealing than...
25
1613
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, 140, 150, 160, 170, 180, 190, 200}; int *ip = ints + 3; What value do the following expressions evaluate to? (Note that it is
14
1863
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 confusing. I think that every element on the stack must be potentially (and equally) available for reference/modification by the executing code. But the quote says that top most element is most accessible element. And so I need your help..... ...
0
10433
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10212
jinu1996
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...
1
10161
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,...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6777
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();...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4112
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
2
3720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2919
bsmnconsultancy
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...

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.