This is the mail archive of the gdb@sources.redhat.com mailing list for the GDB project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Why malloc() when target code is executed?


On Aug 22, 10:48pm, Josef Wolf wrote:

> I just noticed that ``print printf("Hello\n")'' call malloc() on the target
> to allocate the memory for the string. AFAICS, this memory never gets freed.
> Is there any reason not to allocate this memory on the stack? This would
> avoid this memory leak. In addition, this would make it possible to use this
> feature on embedded systems which often have either restricted memory or
> even dont have malloc() at all.

For printf(), allocating the string on the stack is (usually) okay. 
This is because printf() doesn't return a pointer to the string nor
does it write the string pointer to some data structure in the
inferior process.  Functions which did either of these could/would end
up with a dangling pointer if the string were to be allocated on the
stack.  OTOH, using malloc() (and never freeing the allocated space)
ensures gdb won't be responsible for the debugged program having a
dangling pointer reference.  I agree that it is not desirable for gdb
to introduce a memory leak in the debugged process, but it's even
worse for gdb to introduce dangling pointer references.

It might be tempting to special case printf() and perhaps several
other well behaved functions so parameter storage is allocated on the
stack instead of being malloc'd.  However, there is nothing preventing
the debugged process from overriding the usual well behaved function
definitions with less well behaved ones.  So, if this code for special
casing a handful of well behaved functions were added to GDB, there'd
need to be a user settable mode indicating such.  The default for such
a mode should be GDB's current behavior.

Kevin


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]