[prog] free() troubles, pointer arrays

John Clarke johnc+linuxchix at kirriwa.net
Thu Mar 18 11:22:42 EST 2004


On Wed, Mar 17, 2004 at 04:54:34 -0600, ed orphan wrote:

> {     char * * main_ptr;
>       main_ptr = create_buffers( main_ptr );

Are you sure you want to pass an uninitialised pointer to
create_buffers()?  I'm guessing that create_buffers() looks something
like this:

    char **create_buffers(char **p)
    {
        size_t i;

        p = malloc(NUM_BUFFERS * sizeof(*p));
        for (i = 0; i < NUM_BUFFERS; i++)
            p[i] = malloc(BUFFER_SIZE);
            
        return p;
    }

If so, you don't need to pass it the pointer because you're not using
it,  but it's probably a good idea to pass it the number of buffers and
the size of each buffer.  If you do that, then you have a general
purpose routine to create an array of buffers which you can use
elsewhere, rather than something that's only useful this once.  Don't
forget to add error checking after each malloc().

>       for(i=0; i<max_rows; i++)
>            free( * main_ptr[i] );

I think you want:

    free(main_ptr[i]);

and you probably want a free(main_ptr) too.

I'd also suggest that you write a function called delete_buffers() that
frees the memory rather than doing it in main().  Put it right after
create_buffers() so that it's obvious that if one changes, the other
needs to be changed too.  It might not matter for your simple program,
but it's a good habit to get into for when you work on something
bigger.

>   The executable runs just fine, except the compiler gives a warning:
> "warning: passing arg1 of 'free' makes pointer from integer
>   without a cast"

That's because you're passing a char to free, not a pointer.  Most
warnings occur for good reasons.  Don't ignore them - investigate each
one, fix it if you can, only ignore it if you understand why it
occurred and can convince yourself it's not a real problem.


Cheers,

John
-- 
Great. The successor to ILoveYou will be Herpes Simplex. It wouldn't
even need Outlook any more, a promiscuous laptop will do.
            -- Arthur van der Harg


More information about the Programming mailing list