C are pointers erased after function call ends? [duplicate] - c

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 2 years ago.
I have learned that whenever a function ends, every local variable declared inside of it is erased. That's why we must use malloc when declaring an array.
But when I think about that again when a function ends what is really erased (in case I defined an array) is the pointer to that array and not the array itself, So we could simply solve the former problem by returning the pointer.
Here is a look at my code, why did it work while my professor said "we must use malloc"?
#include <stdio.h>
int * test ()
{
int arr[3]={4,5,6};
return arr;
}
int main() {
printf("Hello, World!\n");
int *arr=test();
printf("%d",arr[1]);
return 0;
}
Edit: I'm working according to the C99 standard if that does make a difference.

Option 1:
Change it to static
static int arr[3]={4,5,6};
Lifetime of a static variable is throughout the program. So we can always create a local static array and return it.
Option 2:
Create a struct
struct wrapper {
int arr[3];
};
The reason this is, array members of structures are deeply copied.

Related

declaration of a local array of size 10^6 in c [duplicate]

This question already has answers here:
Getting a stack overflow exception when declaring a large array
(8 answers)
Closed 8 years ago.
I can declare an array of size 10^6 globally in c, but when I declared it inside the main() function it doesn't work.Why is it so?
this statement causes runtime error:
int main()
{
long long arr[1000001];
return 1;
}
but this runs perfectly:
static long long arr[1000001];
int main()
{
return 1;
}
Declaring anything with static means it gets allocated in static memory space. It gets allocated once per program execution, at the beginning, and is never deallocated. Declaring something inside a function (without the static keyword) means it gets allocated on the stack. The stack is much smaller than the static/global memory space.
You can visit the link below for details:
http://www.gnu.org/software/libc/manual/html_node/Memory-Allocation-and-C.html

Returning pointer to local variable [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 8 years ago.
What is the problem associated with returning a pointer to a local variable?
And (i don't know if its legal to do this) What is the problem with returning a reference to pointer in main?
ex:
int *p;
p=abc();
where abc would be returning int&
P.S. Sorry if not clear. I am confused too :P
You can syntactically return a pointer to a local variable, but that variable will no longer be valid after the function has returned.
If your code is:
int *abc() {
int n = 3;
return &n;
}
void foo() {
int m = 4;
}
int main() {
int *p;
p=abc();
foo();
printf("%d", *p);
}
then m will probably overwrite n and the result will be 4.
In simple terms, local variables are available only as long as it is in that function is in the function stack, once the function is done, its popped out of the function stack.

C static variables [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I've been trying to wrap my head around static variables in C and so I wrote this:
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int *pointer;
void stat();
int main()
{
stat();
printf("%i", *pointer);
}
void stat()
{
int c = 2;
pointer = &c;
}
This does work and display 2 in the command line, but I don't understand why.
Doesn't int c cease to exist when the function stat exits? Then what does pointer point to? And how does it retain the value of the integer? Why can I do without making int c static here?
c ceases to exist, but you're still allowed to look at that memory location, and you're getting lucky; the value is still there at that moment-- it hasn't been overwritten by anything else yet.
Your understanding is correct; pointer is pointing at memory you shouldn't be looking at once stat returns.
c as an object ceases to exist.
But your pointer does not cease to exist because it is global.
Your pointer is pointing to the memory address where c was.
It will continue pointing there unless you poi it somewhere else.
But, the content at that address could change if something else is assigned that address or overlaps that in memory later.
I should add that nothing here is a static anything.
The static keyword has special significance and it has a deferent effect depending on the scope in which it is declared.

C returning garbage value for length greater than 3 [duplicate]

This question already has answers here:
Since I can't return a local variable, what's the best way to return a string from a C or C++ function?
(8 answers)
Closed 9 years ago.
I have a main function that has to receive a string.
main()
{
char *c = fun();
}
char* fun()
{
char a[] = "hello";
return a;
}
The problem is that if I return string of lenght 3 or less, then everything is good. If I return string of length > 3, then I receive garbage value along with the string. Why is that ?
You return a pointer to a local variable. The variable is stack-allocated, and it is destroyed when the function exits. Using such pointer is undefined behaviour.
char* fun()
{
char a[] = "hello";
return a;
}
Array a has automatic storage duration. At the end of the function the array object a is destroyed. This means the pointer becomes invalid at the exit of the function and any use of it is undefined behavior.
You are returning an automatic variable, which is a big no-no. That it works at all is an accident of the implementation.
The variable a is local to fun(), and so goes out of scope (and out of existence) when you return. The fact that is works for any case is pure luck. You could make a static, or dynamically allocated, or fix it in ohter ways.

strange behavior in c [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
I recently came across the following code:
#include <stdio.h>
int* abc () {
int a[3] = {1,10,100};
return a;
}
int* xyz () {
int b[1] = {222};
return b;
}
int main() {
int *a, *b;
a = abc();
b = xyz();
printf("%d\n", *a);
return 0;
}
the output is 222. 'a' is pointing to the array declared inside the xyz().
my question is:
why is a pointing to the array declared inside xyz().
the array declared inside the function xyz() should go out of scope after the execution of the function. why is that not happening ?
2: It is happening, and the entire program has undefined behaviour. It is not a correct program, and there's little point musing about ifs and buts.
You might see 222 because the memory that was used for the local array in abc has been used for something else - the stack for the function xyz. And you're passing around an address to that memory. Make a few more function calls and *a may contain some other value.
should go out of scope after the execution of the function. why is that not happening ?
The variable has gone out of scope. Using that address outside the function is incorrect code: using a pointer to local data returned from a function is undefined behavior.
The variables a and b are automatic variables; using their adress in a other function is an undefined behavior. Anything can happen : you can't expect an output (eg, an optimizing compiler can delete some illegal code).
to return a pointer it must be a pointer to dynamically allocated variable or static or global variable.
returning a pointer to a stack variable will cause you to have pointer to the stack which will be reused when you call a new method.
it happened in your case to reuse the stack variable for another array and overwrite the old value stored when you called the first method.
try to call printf again you will see different output because the first call to printf changed the stack content.
why is that not happening ?
It does happen, just formally. Undefined behavior is not obligated to crash or to misbehave - they "anything might happen" means it can also run seemingly without any error. I just answered a similar question.
The functions abc and xyz are each passing back an address to a locally created array. Subsequent calls are mashing the memory that was previously used (and passed back to you).
These are called automatic local variables.
You'll need to declare those arrays as static or allocate the memory in a different way.

Resources