Expert C Programming

(Jeff_L) #1
This solves the problem of anyone overwriting the string. Only routines to which you give a
pointer will be able to modify this static array. However, callers have to use the value or copy
it before another call overwrites it. As with global arrays, large buffers can be wasteful of
memory if not in use.


  1. Explicitly allocate some memory to hold the return value. Example:


17.


18. char *func() {


19. char *s = malloc( 120 ) ;


20. ...


21. return s;


}


This method has the advantages of the static array, and each invocation creates a new buffer,
so subsequent calls don't overwrite the value returned by the first. It works for multithreaded
code (programs where there is more than one thread of control active at a given instant). The
disadvantage is that the programmer has to accept responsibility for memory management.
This may be easy, or it may be very hard, depending on the complexity of the program. It can
lead to incredible bugs if memory is freed while still in use, or "memory leaks" if memory no
longer in use is still held. It's too easy to forget to free allocated memory.


  1. Probably the best solution is to require the caller to allocate the memory to hold the return


value. For safety, provide a count of the size of the buffer (just as fgets() requires in the


standard library).

23.


24. void func( char * result, int size) {


25. ...


26. strncpy(result,"That'd be in the data segment, Bob",


size);


27. }


28.


29. buffer = malloc(size);


30. func( buffer, size );


31. ...


free(buffer);


Memory management works best if you can write the "free" at the same time as you write the
"malloc". This solution makes that possible.

To avoid the "data corruption" problem, note that lint will complain about the simplest case of:


return local_array;


saying warning: function returns pointer to automatic. However, neither


a compiler nor lint can detect all cases of a local array being returned (it may be hidden by a level of
indirection).

Free download pdf