Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

c - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...