Home

"Victor Bazarov" <v.Abazarov@comAcast.net> wrote in message
news:fauola$pep$1@news.datemas.de...
> Jason wrote:
>> How do I free (delete) the memory allocated by this? I know I could
>> change it to
>>
>> char returnArr[8];
>
> You could, but then you'd be returning a pointer to a local variable
> which is a VERY BAD THING(tm).

Ugh.. see, it's a good thing that I asked.

>> but that would prevent me from learning anything new today.
>
> Not only that, it would have UB.

Undefined Behaviour.. see, I remembered. ;-)

> You *could* declare 'returnArr' _static_ in that function, but then
> you have a multithreading disaster.

Yeah, I really don't want to do that because this application eventually
will be multithreaded, and I know all about the agony of shared globals
between threads.

> It is much better to return a 'std::string':
>
> std::string fooFunc(int Bar) {
> std::string returnStr;
> ...
> return returnStr;
> }
>
> of course the places where it's called need to be rewritten as well:
>
> fprintf(filePtr, "%s and stuff", fooFunc(myInt).c_str());

So for now, there's pretty much nothing I can do except leave it. If I
understand correctly, this function will be allocating 8 bytes on the heap
every time it runs? So if it runs for a long time, this could eventually be
disastrous? How was something like this solved in the days of C?

Could I do this?

myCharPtr = fooFunc(myInt);
fprintf(filePtr,"%s and stuff",myCharPtr);
delete[] myCharPtr;

Would that work, or would that give me issues? More UBness?

Thanks for your patience with my naivety.

- Jason

previous
next

Re: File Space Allocation + Writing (C++/Linux)
Re: c++
Re: How to Modify Console output AFTER it has gone to cout
Re: What is best way to implement "tail"?
Re: Looking for the "isfinite" function in C/C++?
Pajacyk
Fundacja Avalon
Mam Marzenie
Podaruj Zycie
Kidprotect