Fundamental error with C code [duplicate] - c

This question already has answers here:
returning a local variable from function in C [duplicate]
(4 answers)
Closed 8 years ago.
I'm studying for exams right and i've come across this question:
What is the crucial error in this code?
int *numbers(int a, int b)
{
int array[2];
array[0] = a * b;
array[1] = a + b;
return array;
}
Now, I don't have much C experience but I don't see a crucial error in this code at all. Maybe I'm being a moron and just overlooking something obvious. The only thing I can see is memory hasn't been allocated using malloc but I don't see that a big problem.
Any help is appreciated!

The most basic problem here is that array ceases to exist as soon as numbers() returns. The returned pointer is pointing to space that will likely be overwritten in just a moment.

The variable array will disappear when the function returns, but you have returned a pointer to its place in memory.

You are basically returning garbage, because array will go out of scope after return. If you make array static everything will be OK.

If memory WAS allocated with malloc, then the function would be valid. Once the function exits, any memory that was allocated within the scope of the function (stack) is no longer valid.

Related

C pointers and var scopes [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 5 years ago.
I've a question about var scopes and pointer.
That's an example function:
int *double(int a)
{
int p = a*2;
int *ret = &p;
return ret;
}
And that's the question:
After a fuction return to the caller, it should delete from the memory every variable declared in it.
In this function I only return the addres of "p" (that's declared only in the function) but when I use it in the main, for example, the space of memory allocated by the function "double" hasn't been deleted.
Why?
The memory isn't valid anymore; what happens when you access it after double has returned is undefined behavior. That means that anything is possible:
It could be that the value hasn't been overwritten by something else yet (what likely happened in your case).
It could be that something else has written something to that address, so the value is now random garbage.
It could be that your code opens up a wormhole to a parallel dimension, causing an invasion of evil space octopi that dooms us all.
So, basically, I don't recommend it.

When is this the memory reserved for this array deallocated? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
Though a similar question has been asked Is it possible to deallocate a statically defined array? previously, I have a related query.
int* foo()
{
int arr[3] = {1, 2, 3};
return arr;
}
int bar(const int*)
{
doSomething with int*;
}
int main()
{
bar( foo() );
}
When will the memory allocated to arr in foo() be deallocated? Is a statically allocated array like arr not usually automatic? This syntax seems to work though, so is the memory assigned to arr only deallocated after the completion of bar()? Or not even then? If not, how would I free it?
Edit: Sorry, forgot to include main. Yes, this appears to be a duplicate post.
Your array behaves like a normal variable, as it actually is one.
The variable scope in C or C++ is usuablly definied by the current block, which is your function foo.
As your array arr lies within the stack-area of your programm you should never every return a pointer to a local variable.
The stack-memory section is invalidated after your foo function returns and so you would access to not permitted memory area if you dereference the return value of foo. This leads to undefined behaviour. So everything can break or nothing. But this is just not what you want.
If you want to return a more long living array, you allocate memory in the heap-memory-section by creating your array with new or malloc. Than you can access it after your foo-function returned. But you have to free or delete[] your array than by hand.
You should maybe read more about memory-layout in C/C++: http://www.geeksforgeeks.org/memory-layout-of-c-program/
Most likely, it will be created on the stack inside the call to foo. When foo exits, the stack pointer is reset. The array is considered no longer accessible.
You can still see it because your program owns the memory where the stack is. However, once something else gets pushed onto the stack, it will get overwritten.
So, you should not use it outside of foo.

Function returning array practices [duplicate]

This question already has answers here:
Declaring a C function to return an array
(5 answers)
Closed 9 years ago.
I have just started my back-to-the-roots project; learning C. I'll be honest, abstraction is nice when you need to plow out a desktop/server application, but with C, things get personal. Which is nice, for a change!
Now to the point; I'm reading into using arrays with functions (Programming in C, Stephen G. Kochan.) I have learnt that when passing an function as a parameter the compiler will always see the reference as a pointer, like so:
void foo (char *array);
Take this, for example:
void foo (char *a)
{
a[0] = 'R'; // side effect
}
int main (void)
{
char a[] = "The quick brown fox jumps over the lazy dog!";
foo (a);
}
I haven't come by information on functions returning arrays or pointer to an array. The function rather changes the array in its parameter, thus causing side effects (as seen above).
Is it possible for a function to return a pointer to an array? Or is the above method just preferred?
Thanks in advance for those that can offer an explanation.
A function can return a pointer to the first element of an array, but it's more problematic, you either have to malloc the memory (like strdup) for the array or have a static array (like ctime).
malloc gives the problem of having to remember to free the memory (memory leaks), static means the array changes with each call, therefore passing an existing array is easier.
I am not sure I follow. Your function is of type void. Are you trying to modify the array by passing it as reference?
In C, if you return a pointer to the first element of the array, you effective return the entire array because C arrays are contiguous in the programs memory (may be not in physical memory). So when you return the pointer to the first element, you effectively tell your main function where the entire array is stored.

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.

local memory address is valid after function return? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
I was refreshing the knowledge about how memory internally works, and I faced the confusion. Here is sample code
int * func(){
int retval = 3;
return &retval;
}
int main(void){
int *ptr = func();
printf("address return from function %p and value %d\n", ptr, *ptr);
}
My understanding regards how stack memory works on a routine, is when a function was called, it is pushed on the stack. And lifetime of local variables within this routine would no longer valid once the function returns. So returning address of local variable seems like not valid, but when I test this code, it actually returns its address and still valid after the function returns.
am I misunderstanding the concept ? Appreciated any comments, Thanks.
"Testing the code" is not a meaningful way to determine if something is valid or not. Your code produces undefined behavior. One possible manifestation of undefined behavior is that the code might appear to be "working". In other words, you simply got lucky.
To answer the question: no, it is not valid to return a pointer to a local variable and it is not valid to dereference such a pointer. Any attempts to do so lead to undefined behavior.

Resources