0

I'm working on a software using a home-made report library which takes only (const char *) type as an argument :

ReportInfo(const char* information); ReportError(const char* error); [...] 

As I'm trying to report value of integers, I'd like to get a representation of those integers in a const char* type. I can do it that way :

int value = 42; string temp_value = to_string(value); const char *final_value= temp_value.c_str(); ReportInfo(final_value); 

It would be great if I could do it without instancing the temp_value. I tried this :

int value = 42; const char* final_value = to_string(value).c_str(); ReportInfo(final_value); 

but final_value is equal to '\0' in that case.

Any idea how to do it ?

8
  • 1
    I don't get the line "but final_value is egal to '\0' in that case." Commented Aug 5, 2015 at 9:11
  • Is there a shortage of newline characters in your work environment? Can you not spare the piddlingly small amount of memory needed for temp_value? :-) Commented Aug 5, 2015 at 9:12
  • Worth reading too: stackoverflow.com/questions/10006891/… Commented Aug 5, 2015 at 9:27
  • @DavidHaim When I debug this part of my code, i can see that the value in final_valueis '\0'. It doesn't make sense to me. Commented Aug 5, 2015 at 9:31
  • @augustin-r Because undefined behaviour doesn´t make sense. It´s a dangling pointer, nothing less or more. Commented Aug 5, 2015 at 9:35

2 Answers 2

6

You could try

ReportInfo(to_string(value).c_str()); 

because the temporary will not be destroyed until ReportInfo returns.

Sign up to request clarification or add additional context in comments.

Comments

4

to_string(value) returns a temporary, so in your second example its lifetime ends at the end of the expression. so you have dangling pointer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.