473,408 Members | 2,734 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,408 software developers and data experts.

pointer usage in c

I write a small program.

char *foo(void);
char *a = "I like C";

int main(void) {
if((strcmp(a,foo())) {
printf("\n i like c");
}
}

char *foo(void)
{
char b[100] = "I like C";
return b;
}

My teacher tells me that this program not work since the return value
from function foo() is not guaranteed to be preserved. I think this is
correct usage of pointers.

I dont think so. I think my teacher wrong.

Please explain.
thanks you
Rick

Nov 14 '05 #1
9 1932
rs******@gmail.com wrote:
char *foo(void);
char *a = "I like C";

int main(void) {
if((strcmp(a,foo())) {
printf("\n i like c");
}
}

char *foo(void)
{
char b[100] = "I like C";
return b;
}

My teacher tells me that this program not work since the return value
from function foo() is not guaranteed to be preserved. I think this is
correct usage of pointers.

I dont think so. I think my teacher wrong.


Your teacher is(!) right. You're returning the address of an auto
("local") array from foo(). This array, like all auto objects, has
automatic duration, which means that once you return from foo(), it goes
out of existence, and any attempt to use it invokes undefined behaviour,
which means it may do anything from appearing to work correctly to crash
hard. Sure, it may _look_ like it still exists after the return, in this
simple test program. However, you cannot rely on this at all. In any
more realistic program you're likely to read garbage.

Richard
Nov 14 '05 #2
rs******@gmail.com wrote:
I write a small program.
#include <string.h>
char *foo(void);
char *a = "I like C";

int main(void) {
if((strcmp(a,foo())) {
printf("\n i like c");
You should in general terminate an output line with a newline in
order to guarantee that it appears.
}
}

char *foo(void)
{
char b[100] = "I like C";
return b;
}

My teacher tells me that this program not work since the return value
from function foo() is not guaranteed to be preserved. I think this is
correct usage of pointers.

I dont think so. I think my teacher wrong.


Your teacher is correct. The array b is not guaranteed to
continue to exist after foo() returns. It might, for instance,
be in a location that is not accessible after the function
returns, or it might get overwritten. Make it static and it will
work.

--
Thomas M. Sommers -- tm*@nj.net -- AB2SB

Nov 14 '05 #3
rs******@gmail.com writes:
I write a small program.

char *foo(void);
char *a = "I like C";

int main(void) {
if((strcmp(a,foo())) {
printf("\n i like c");
}
}

char *foo(void)
{
char b[100] = "I like C";
return b;
}

My teacher tells me that this program not work since the return value
from function foo() is not guaranteed to be preserved. I think this is
correct usage of pointers.

I dont think so. I think my teacher wrong.


As others have pointed out, your teacher is right.

Your array b is local to the function foo. As soon as foo returns,
the array ceases to exist, and any attempt to refer to it will invoke
undefined behavior.

You've probably been misled by the fact that the program *appears* to
work properly. That's the worst thing about undefined behavior; it's
not guaranteed to blow up. What probably happens in your program (for
a typical C implementation) is that the memory that the array occupied
is still there; it's just beyond the top of the stack. It *could* be
re-used for some other purpose. For example, an interrupt could be
triggered after foo() returns and before you use the value, clobbering
it. Or the system could mark the memory space as unavailable, causing
a trap when you try to access it. But the most likely thing is that
it's still right where you left it. Accessing it is still an error,
but the implementation isn't required to detect the error.

By returning from foo() you've told the system that you're finished
with the array. By attempting to use the array afterwards, you're
lying to the system. It's not obligated to show you any kind of
mercy. So don't do that.

--
Keith Thompson (The_Other_Keith) 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 14 '05 #4
On Wed, 11 May 2005 00:01:06 -0700, rskeples wrote:
I write a small program.

char *foo(void);
char *a = "I like C";

int main(void) {
if((strcmp(a,foo())) {
printf("\n i like c");
}
}

char *foo(void)
{
char b[100] = "I like C";
return b;
}

My teacher tells me that this program not work since the return value
from function foo() is not guaranteed to be preserved. I think this is
correct usage of pointers.
The problem is not with the return value directly, it is with what the
return value is pointing at. A pointer value is only valid as long as the
thing it points at still exists. The return value of foo() isn't b itself
or a copy of b, it is a pointer to (the first element of) b. When foo()
returns all of its automatic variables cease to exist and that includes b,
and so any pointer to b becomes invalid. In main() you are trying to use
the value of an invalid pointer which gives undefined behaviour.
I dont think so. I think my teacher wrong.


Remember that a pointer and what it points at are separate things and you
have to consider both.

Lawrence
Nov 14 '05 #5
> My teacher tells me that this program not work since the return value
from function foo() is not guaranteed to be preserved. I think this is
correct usage of pointers.


Your teacher is correct. The memory for "b" is garbage once the
function returns. In order to make it right, you need to allocate
memory from the heap, and copy the string into the heap.

Here is an untested function, but which should do you right:

char *foo(void)
{
char b[100] = "I like C"; /* this will go away when the function returns */
char *c = malloc((strlen(b) + 1) * sizeof(char)); /* malloc enough
memory to hold "I like C" -- this will NOT go away when the function
returns */
strcpy(c, b); /* copy the contents of b to c */

return c; /* return c */
}

Note that since you allocated the memory with malloc, when you are
finished with it you MUST deallocate it with free().

Jon
----
Learn to program using Linux assembly language
http://www.cafeshops.com/bartlettpublish.8640017
Nov 14 '05 #6
Jonathan Bartlett:
....
return c; /* return c */


Very enlightening comment. :-)

Jirka
Nov 14 '05 #7
rs******@gmail.com wrote on 11/05/05 :
char *foo(void);
char *a = "I like C";

int main(void) {
if((strcmp(a,foo())) {
printf("\n i like c");
}
}

char *foo(void)
{
char b[100] = "I like C";
return b;
}

My teacher tells me that this program not work since the return value
from function foo() is not guaranteed to be preserved. I think this is
correct usage of pointers.

I dont think so. I think my teacher wrong.


Yes, so is my compiler...

main.c:13: warning: initialization discards qualifiers from pointer
target type main.c: In function `main_':
main.c:16: warning: implicit declaration of function `strcmp'
main.c:16: parse error before '{' token
main.c: In function `foo':
main.c:24: warning: function returns address of local variable

"Please engage your brain..." (c) Dan Pop...

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

..sig under repair

Nov 14 '05 #8
(supersedes <mn***********************@YOURBRAnoos.fr>)

rs******@gmail.com wrote on 11/05/05 :
char *foo(void);
char *a = "I like C";

int main(void) {
if((strcmp(a,foo())) {
printf("\n i like c");
}
}

char *foo(void)
{
char b[100] = "I like C";
return b;
}

My teacher tells me that this program not work since the return value
from function foo() is not guaranteed to be preserved. I think this is
correct usage of pointers.

I dont think so. I think my teacher wrong.


Yes, so is my compiler...

main.c:13: warning: initialization discards qualifiers from pointer
target type main.c: In function `main_':
main.c:16: warning: implicit declaration of function `strcmp'
main.c:16: parse error before '{' token
main.c: In function `foo':
main.c:24: warning: function returns address of local variable

"Please engage your brain..." (c) Dan Pop...

#include <string.h>
#include <stdio.h>

char const *foo (void)
{
char const *b = "I like C";
return b;
}

int main (void)
{
char const *a = "I like C";

if (strcmp (a, foo ()) == 0)
{
printf ("I like c\n");
}
return 0;
}

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

..sig under repair

Nov 14 '05 #9
Hi All,

I think the following code will also work:

char *foo( )
{
return "I like C";
}

since string-literals have static life-time ( regardless of scope) !.

Nitin

Nov 14 '05 #10

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

Similar topics

7
by: Dave | last post by:
Hello all, In the code below, I use a pointer to an object under construction. Is the usage below legal? I have come across similar code at work. It compiles, but I'm not sure it's really...
8
by: Frank Münnich | last post by:
Hi there.. My name is Frank Münnich. I've got a question about pointers that refer to an array of a structure. How do I declare that type? If I have declared a structure struct mystruc {...
42
by: baumann | last post by:
hi all, typedef int (*pfunc)(int , int); pfunc a_func; i know it's ok, but how can define a_func without typedef statement? thanks .
204
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 =...
41
by: Alexei A. Frounze | last post by:
Seems like, to make sure that a pointer doesn't point to an object/function, NULL (or simply 0) is good enough for both kind of pointers, data pointers and function pointers as per 6.3.2.3: 3 An...
9
by: John Veldthuis | last post by:
Hi, I want to be able to read a https web page, enter a user name and password in the fields returned and then read in the information that is returned after this and then close the connection. ...
41
by: Summercool | last post by:
Can we confirm the following? also someone said, Java also has "reference" like in C++, which is an "implicit pointer": Pointer and Reference --------------------- I am starting to see what...
13
by: Prisoner at War | last post by:
I know about the * * style="cursor: pointer; cursor: hand;" * * attribute of the <imgtag, but is there a way JavaScript can "load in" one's own graphic for such events?? How? TIA!
50
by: Juha Nieminen | last post by:
I asked a long time ago in this group how to make a smart pointer which works with incomplete types. I got this answer (only relevant parts included): ...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.