0

sorry looks like similar questions have been asked a lot but I did not found any which really answers my question.

I am using a library function which returns const char *.

Within a function I am calling this library multiple time with a different string as result every time.

May example code explain:

void myfunc()
{
const char *string;
json_object *json;

/* Doing stuff, assigning data to *json */

// calling the function 
// DEF: const char* json_object_to_json_string(struct json_object * obj)    
string = json_object_to_json_string(json);

// doing stuff (strcpy etc.) with string
/* doing other stuff, never "free(string)" */
return;
}

So as the library function every time returns back a const char* (where content is different from previous call) when will the memory be released? Never? Within which functions can I access the content?

Soory, I am a little bit confused about this.

Thanks for letting me know!

/KNEBB

Christian
  • 169
  • 8
  • 3
    Depends entirely on the library function that returns the string. Is it returning the same `static` buffer for every call, or is it allocating it dynamically (such as with `malloc`)? If dynamically, it should probably document that the caller must free the returned string. If it's the same static buffer, it will be overwritten by the next call to that library function, and thus you need to copy it if you wish to keep it past that. – Arkku Oct 20 '21 at 09:34
  • Not necessarily! It depends what `json_object_to_json_string` is doing. Read the documentation. – Support Ukraine Oct 20 '21 at 09:34
  • 1
    See the linked duplicate. The memory is allocated in the `json` object, the pointer just points at that data. So whether this code has a leak or not depends entirely upon `/* Doing stuff */` – Lundin Oct 20 '21 at 09:36
  • Damn! I did not search for json stuff. Anyways, the linked question answers mine, too. Thanks @Lundin – Christian Oct 20 '21 at 09:42

0 Answers0