Using a C but not a C++ compiler. We have code like this:

Suppose we have code like this:

main()
{
     int *funcko();
     int *george = funcko();
     printf("%d", goerge[3]);
}

int *funcko()
{
     int cat[12];
     return cat;
}

What happens when you try this according to the actual rules of C? I am aware that cat
is supposed to be banished after the return, although I would expect the pointer to actually be transmitted to george. However, I don't think it remains an array. Just a lonely pointer?

But I would like to know what the C standard really tells us here.

Edited 5 Years Ago by Narue: Added code tags

When the function 'funcko' returns the pointer to cat becomes invalid because the program releases its memory. Maybe releases is a bad way of putting it, the program makes the memory available for other uses.

Edited 5 Years Ago by gerard4143: n/a

Using a C but not a C++ compiler.

Irrelevant. Both languages follow the same rule.

But I would like to know what the C standard really tells us here.

The C standard says that it invokes undefined behavior. See section 6.2.2:

If an object is referred to outside of its lifetime, the behavior is undefined.

and section 6.2.5:

For such an object that does not have a variable length array type, its lifetime extends
from entry into the block with which it is associated until execution of that block ends in
any way.

I think I have not quite asked what I really meant, though I thank you for your replies. I don't care about cat. Of course it is history. I care about george, which has had cat sent to it. Is george a pointer to a single integer? Is george acrually an array of size 12 as ws cat? Is george just nothing valid for anything? My real question is to find how george is supposed to behave.

My real question is to find how george is supposed to behave.

george points to the same memory that was previously occupied by cat . So you should care greatly about the fate of cat because it determines the validity of george .

This article has been dead for over six months. Start a new discussion instead.