0

Consider I have a C function:

MyFunction(const char *value, bool trigger)

Inside, depending on the value of the trigger variable, I'd like to either use a value provided to the function or simply overwrite it with some other const char string returned by a different function, e.g.:

MyFunction(const char *value, bool trigger) {
if (trigger) {
     value = anotherFunctionReturningConstChar().c_str();
}
// do processing here

}

What is the correct way to achieve this, considering the pointers and their type. As far as I understand, I cannot simply change the value of the function parameter and I need to use some third variable which should be set to either a value or to the result of anotherFunction.

I'm getting the following error right now in the static analyzer: [ID:danglingTemporaryLifetime] Using pointer to temporary.

What does it mean and how can I overcome it?

273K
  • 29,503
  • 10
  • 41
  • 64
Richard Topchii
  • 7,075
  • 8
  • 48
  • 115
  • Does this answer your question? [Why does calling std::string.c\_str() on a function that returns a string not work?](https://stackoverflow.com/questions/35980664/why-does-calling-stdstring-c-str-on-a-function-that-returns-a-string-not-wor) – 273K Nov 04 '21 at 16:15

2 Answers2

1

No, you can assign to a function parameter exactly as you did. This doesn't affect the caller in any way.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • I tried that, but getting the following error: ` [ID:danglingTemporaryLifetime] Using pointer to temporary.` – Richard Topchii Nov 04 '21 at 15:26
  • 1
    @RichardTopchii We'll need a [mcve]. – HolyBlackCat Nov 04 '21 at 15:31
  • Updated my question, the code actually works well, but I'm getting the static analyzer error now. Curious, what does it mean and how can I overcome it. – Richard Topchii Nov 04 '21 at 15:53
  • Maybe this is also relevant: https://stackoverflow.com/questions/35980664/why-does-calling-stdstring-c-str-on-a-function-that-returns-a-string-not-wor – Richard Topchii Nov 04 '21 at 15:55
  • 2
    @RichardTopchii Assuming `anotherFunctionReturningConstChar` returns by value, this is UB, since the string dies immediately, and the pointer becomes dangling. You need to save the result to a local `std::string` variable, call `.c_str()` on that variable, and ensure that it lives as long as you want to use the pointer. – HolyBlackCat Nov 04 '21 at 16:50
-1

use MyFunction(void *value, bool trigger) where you hold a pointer to a function or to a const char* and then cast the value to the desired object but I think it is useless.

Anis Belaid
  • 304
  • 2
  • 8