I'm still comparatively new to C++ but I'm mostly working off of C++11 features which generally save me from memory leaks. Still, working with other older libraries, there's unfortunately times I need to interface with older code.
I've seen similar questions, but couldn't easily locate one where the array was allocated without new
; eg, so it's on the stack rather than the heap, to my understanding.
This situation happens to involve a string, but the mechanics are probably more to do with arrays.
ConfigStruct {
const char *word;
}
ConfigStruct generateConfigStruct() {
const char myWord[] = "word"; // <-- This
ConfigStruct cfg;
cfg.word = myWord;
return cfg;
}
I believe this configuration object is going to be passed into a separate lower-level function. But, I'm having a hard time working out where the memory responsibilities should be in this case. Is the low-level library the only thing that can release that string's memory? Will it get destructed with the ConfigStruct automatically? Or, will that memory be inappropriately marked as "free" at the end of this function, and possibly cause the configuration object issues later?
EDIT: One final follow-on question; if ConfigStruct
cannot be changed, and my task is to write a generateConfigStruct
that returns a ConfigStruct
, is there any way to do it that won't cause later usage any issues, and can somehow guarantee memory safety despite the dangling pointer?