Functions returning a char pointer

I came across many functions that return char pointers in one deprecated application. Some of them return pointers to local character arrays. It seems to cause it to crash after several calls (not immediately!). See below for usage

char *f1(){
  char buff[20];
  char *ptr;

  ----
  ----
  ptr=buff;
 return ptr;
}

---
---

f2(f1());

f1 () returns a local pointer variable, and then passes it to another function. I got the error right away when it was compiled using _DEBUG mode in MS DEV. But in release mode, it does not cause an immediate failure, but can occur after many calls.

When I changed the usage as shown below, it works without any problems. Is the following use safe?

strcpy(arr,f1()); /* arr is fixed char array*/
f2(arr);
+5
source share
12

, undefined. , .

+12

, . strcpy , , .

+3

malloc , , . ( ). .

+3

f1 (buff), . malloc() .

+2

. , . :

  • ,
  • ( , Win32 API)
  • ++ std::string
+2

?

.

-, , :

char *safe_f1(void) {
    char *ptr;
    ptr = (char *) malloc(20 * sizeof(char));
    ...
    return ptr;
}
+2

. :

, . , , , .

, , char buff[20], buff ptr ( ptr=buff). , ( ), function/block , , ptr.

strcpy, , , strcpy , buff. , .

, , .

malloc, malloc , . , ( ).

, , ptr, .

: , , ptr, , , , , . : -)

, ... : -)

PS: , ( ), - :

{
  char safe_buffer[20];
  char *unsafe_ptr;
  int i;
  unsafe_ptr = f1();
  /*Copy the buffer without calling any function
    not to change the stack content
  */
  for(i=0;i<20 && *(unsafe_ptr + i) != 0;i++)
  {
    *(safe_buffer + i) = *(unsafe_ptr + i);
  }
  *(safe_buffer + i) = 0;
  f2(safe_buffer);
}
+2

.. .

, strcpy(arr,f1());, , , , .

+1

, , buff[20] f1. , f1.

buff[20] , malloc f1. - buff[20] f1 ( , f1), f1. f1 .

+1

, f1(), malloc(). .

0

:

  • char buff[20] f1, , strcpy.

  • Use return strdup (ptr);and freepointer out f1. This is easier to use than malloc(although technically the same). It is slower than 1. but thread safe.

0
source

I would suggest changing these functions to take a pointer that uses

void f1(char *)

Thus, each piece of code that calls the function must make a decision about where the memory is written and delete any allocated memory.

0
source

All Articles