Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functions returning char pointer

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);
like image 473
cobp Avatar asked Feb 26 '10 12:02

cobp


People also ask

How do I return a char pointer?

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.

Can a function returns pointer?

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.

What type of function returns a pointer?

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.

Can you return char [] in C?

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.


2 Answers

No, it is undefined behaviour. It just happens to work in your case, but may stop working at any time.

like image 180
qrdl Avatar answered Oct 08 '22 04:10

qrdl


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.

like image 29
Richard Pennington Avatar answered Oct 08 '22 04:10

Richard Pennington