simple question -- memory leak i am not sure about

Simple question i am sure..

This is compiled on solaris 10

Reading specs from /usr/local/lib/gcc/sparc-sun-solaris2.10/3.4.6/specs
Configured with: ../configure --with-as=/usr/ccs/bin/as --with-ld=/usr/ccs/bin/ld --enable-shared --enable-languages=c,c++,f77
Thread model: posix
gcc version 3.4.6

$ while true
> do
> ps -aefl -o pmem,osz,vsz,pid,comm |egrep a.out
> sleep 2
> done
0.0 154 1232 3526 ./a.out
0.0 154 1232 3526 ./a.out
0.0 155 1240 3526 ./a.out
0.0 156 1248 3526 ./a.out
0.0 156 1248 3526 ./a.out
0.0 157 1256 3526 ./a.out

$ cat gcctest.c test_malloc.c


main() {

while (1) {

sleep (3);




char *test_malloc() {

char *pointer;

pointer = malloc(8192);

sprintf(pointer, "some data to return


I can't call free in test_malloc() function since I am doing a return, and calling free in the gcctest.c for the pointer gives it as undefined. What is the right way to handle this to avoid memory leaks?


  • The answer is different for C and C++. Assuming C.

    Strictly speaking, the correct way to handle it is to never allocate memory inside functions. Easier said than done, but the vast majority of memory leak bugs comes from functions that don't leave the memory allocation to the caller.

    The reasons for this are:

    - Code that has nothing to do with memory allocation should not concern itself with memory allocation. This is fundamental program design: a code made to do one task should only do that task and nothing else.

    - The code module that allocates the data is also responsible for freeing it.

    As I see it, the only time dynamic allocation inside functions is acceptable practice, is when you wish to allocate private data for a program module:

    [code]static unsigned char* _data;
    static unsigned int _data_size;

    BOOL module_init (unsigned int n)
    BOOL result;

    _data = malloc(n);

    if(data == NULL)
    _data_size = 0;
    result = FALSE;
    _data_size = n;
    result = TRUE;

    return result;

    void module_terminate (void)

    The code in "module" will have to handle all allocation in this case.

    In all other cases when you are not dealing with private data, you should never allocate memory inside functions. Allocation should always be made by the caller. (For example, the whole Windows API is built on this principle)

    [code]void do_something(unsigned char* data, unsigned char data_size);

    int main()
    unsigned char* data;
    data = malloc(N);

    /* assign values to "data" */

    do_something(data, N);
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion