I came across lot of functions returning char pointers in one legacy application. Some of them returning pointers to local character arrays. It seems to be causing crashes after several invocations(not immediately!) see the usage below
char *f1(){
char buff[20];
char *ptr;
----
----
ptr=buff;
return ptr;
}
---
---
f2(f1());
f1() returns a pointer local variable and then passes it to another function. I got the crash directly when it's compiled using _DEBUG mode in MS DEV. But in release mode, it doesnt cause an immediate crash, but it might occur after making lots of such calls.
When I modified the usage as below, it's working without any issues. Is the following usage safe?
strcpy(arr,f1()); /* arr is fixed char array*/
f2(arr);
One solution is to allocate the appropriate amount of memory in the main function, and pass the pointer to the memory to the helper function. Show activity on this post. you shouldn't return data that sits on automatic storage, when you return it goes out of scope. scope and storage duration are two different beasts.
We can pass pointers to the function as well as return pointer from a function. But it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns.
Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.
Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string.
No, it is undefined behaviour. It just happens to work in your case, but may stop working at any time.
No that's is not safe. Just calling strcpy can modify the stack enough to cause problems later because the return address and parameters might over-write the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With