473,624 Members | 2,252 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why this code is working

Hi,
Please look at the following code. In my opinion, the value of "char
*str" in the main function should not change even after calling the
function "funct" and that's beacuse the "char *str" in the function
funct is local to the function funct and therefore it's value will be
meaningless when the function funct returns. But still the value of
"char *str" in the main function is changing after calling the function
funct. Can anybody help me?
#include <stdio.h>

char *funct()
{
char *str = "This is a local string";
return str;
}

int main(void)
{
char *str;
str = "This is a test";
printf("%s\n",s tr);
str = funct();
printf("%s\n",s tr);
return 0;
}

Nov 15 '05 #1
7 1337
jammie_li...@ya hoo.com wrote:
Please look at the following code. In my opinion, the value of "char
*str" in the main function should not change even after calling the
function "funct"
main()'s str is being assigned to the return value of funct()
and that's beacuse the "char *str" in the function
funct is local to the function funct and therefore it's value will be
meaningless when the function funct returns.
No, funct()'s str ceases to exist *after* the call to funct()
completes. The value returned by funct(), on the other hand, is a
perfectly valid value.
But still the value of
"char *str" in the main function is changing after calling the function
funct.
Of course it is. You're assigning it to a new value. It changes just
like any other assignment statement would make it change.
#include <stdio.h>

char *funct()
{
char *str = "This is a local string";
return str;
You are returning the *value* that str holds at this point in the code.
That is, funct() returns the string "This is a local string"
}
"Here", funct() has ended, and so funct()'s str no longer exists. But
the value has already been returned.
int main(void)
{
char *str;
str = "This is a test";
Here you assign a value to main()'s str
printf("%s\n",s tr);
str = funct();
Here you call funct(), and assign funct()'s return value to main's
str(). This has precisely the same side effect as:
str = "This is a local string";
printf("%s\n",s tr);
return 0;
}


It may be the fact that main()'s str and funct()'s str variables happen
to have the same name, but other otherwise completely unrelated, that
is confusing you.

Paul Lalli

Nov 15 '05 #2
But when a function returns, the compiler reclaims all the memory
assigend to the local variables. By this theory, isn't it possible that
the memory where the string "This is local to the function" was
stored, would also be reclaimed. In that case, the main's function str
will be pointing at a totally meaningless position.

Nov 15 '05 #3
ja**********@ya hoo.com wrote:
But when a function returns, the compiler reclaims all the memory
assigend to the local variables. By this theory, isn't it possible that
the memory where the string "This is local to the function" was
stored, would also be reclaimed. In that case, the main's function str
will be pointing at a totally meaningless position.


No, because the string "this is local to the function" is *not* local to
the function. String literals always have static duration, no matter
where you declare them. The string literal continues to exist even after
the function returns.

If you had instead used the string literal as an initialiser for a local
array, then it would have returned an invalid pointer as you seem to expect.

Compare the following functions:

char *funct1()
{
char *str = "This is a string literal with static duration.";
return str;
}

char *funct2()
{
char str[] = "But this one is used to initialise a local array.";
return str;
}

The [] in funct2 make all the difference. Funct1 returns a valid
pointer, but funct2 returns an invalid pointer.

--
Simon.
Nov 15 '05 #4
Simon wrote :
"String literals always have static duration, no matter
where you declare them."

Is the same is also true when you allocate memory via malloc and other
related function like in the case below:
Also, in this code the getnode() is not returning anything explicitly(
even though it should), still it is implicitly returning the value of
node * q defined locally in it. Is this what the standard says or is
happening at the mercy of the compiler?

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
int data;
struct node * next;
}node;

node * getnode()
{
node * q = malloc(sizeof(n ode));
if(q == NULL)
{
printf("Insuffi cient memory\n");
exit(1);
}

q->data = 9;
q->next = NULL;
}

void display(node *q)
{
if(q == NULL)
{
printf("q is NULL in display\n");
exit(1);
}
printf("%d %p\n",q->data, (void*)q->next);
return;
}
int main(void)
{
node * q;

q = getnode();
display(q);
return 0 ;
}

Nov 15 '05 #5
ja**********@ya hoo.com wrote:
Simon wrote :
"String literals always have static duration, no matter
where you declare them."

Is the same is also true when you allocate memory via malloc and other
related function
Similar. The memory block allocated by the 'malloc', 'calloc' or
'realloc' functions will remain valid until the base address of the
block is passed to the 'free' function. It doesn't matter whether the
pointer gets passed to or from functions.
like in the case below:
Also, in this code the getnode() is not returning anything explicitly(
even though it should), still it is implicitly returning the value of
node * q defined locally in it.
It's not implicitly returning anything. The code is wrong, and will not
compile.
Is this what the standard says or is
happening at the mercy of the compiler?
After you fix the errors below, the code is valid according to the
standard. It should compile and run on all C compilers.
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
int data;
struct node * next;
}node;

node * getnode()
{
node * q = malloc(sizeof(n ode));
if(q == NULL)
{
printf("Insuffi cient memory\n");
exit(1);
The exit code 1 is not defined by the C standard, and could have
unintended effects. If you want to indicate that the program failed, you
should write
exit(EXIT_FAILU RE);
}

q->data = 9;
q->next = NULL;
You should have the line
return q;
here.
}

void display(node *q)
{
if(q == NULL)
{
printf("q is NULL in display\n");
exit(1);
}
printf("%d %p\n",q->data, (void*)q->next);
return;
}
int main(void)
{
node * q;

q = getnode();
display(q);
You should have the line
free(q);
here.
return 0 ;
}


Once you correct the errors shown above, this code is fine.

--
Simon.
Nov 15 '05 #6
ja**********@ya hoo.com writes:
But when a function returns, the compiler reclaims all the memory
assigend to the local variables. By this theory, isn't it possible that
the memory where the string "This is local to the function" was
stored, would also be reclaimed. In that case, the main's function str
will be pointing at a totally meaningless position.


Don't assume your readers can see the article to which you're
replying. You need to provide some context in the form of properly
attributed quotations from the parent article (not necessarily the
whole thing, just what's relevant to your reply). See nearly any
followup in this newsgroup for an example.

Google Groups makes this gratutiously difficult. Please follow these
instructions (which have been posted here over 1000 times), and
*please* complain to Google about their broken interface, which
they've persistently refused to fix.

If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #7
On 2005-10-31, ja**********@ya hoo.com <ja**********@y ahoo.com> wrote:
But when a function returns, the compiler reclaims all the memory
assigend to the local variables. By this theory, isn't it possible that
the memory where the string "This is local to the function" was
stored, would also be reclaimed.


No, the string "This is local to the function" in this situation is
in static storage, because it is a string literal not being used to
initialize an array.
Nov 15 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

171
7687
by: tshad | last post by:
I am just trying to decide whether to split my code and uses code behind. I did it with one of my pages and found it was quite a bit of trouble. I know that most people (and books and articles) like it because you can split the code from the design. That is logical. But if you are the only one working on the code, it seem a little overkill. I use Dreamweaver to do my design and find it a bit of a hassle to have multiple files open...
17
2691
by: tshad | last post by:
Many (if not most) have said that code-behind is best if working in teams - which does seem logical. How do you deal with the flow of the work? I have someone who is good at designing, but know nothing about ASP. He can build the design of the pages in HTML with tables, labels, textboxes etc. But then I would need to change them to ASP.net objects and write the code to make the page work (normally I do this as I go - can't do this...
0
1580
by: George2 | last post by:
Hello everyone, From the definition of working set, it is a subset of virtual pages resident in physical memory -- from book Windows Internals. It means working set could not be larger than virtual memory (subset relationship). But the following simple code on Windows Server 2003 proves (if you monitor virtual bytes counter and working set bytes conuter from perfmon), if we do not unmap the page map file, the working set will continue to...
0
8242
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8177
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,...
0
8681
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
8629
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...
0
8488
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7170
agi2029
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...
1
6112
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...
1
2611
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
1
1793
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.