[splint-discuss] Splint and malloc

Roland Illig roland.illig at gmx.de
Mon Feb 23 01:35:48 PST 2009


Phil Longstaff schrieb:
> Is there any way of indicating to splint that if a struct with pointers
> is malloc'ed and the pointers are given values, that the previous values
> don't need to be freed because it is new memory?
> 
> Example:
> 
> typedef struct {
> 
> char* x;
> 
> } struct_t;
> 
> struct_t* s = malloc( sizeof(struct_t) );
> 
> s.x = malloc(10);
> 
> will give a warning that s.x is implied only and hasn't been freed,
> leading to memory leak. However, since s is pointing to new storage,
> there isn't anything to be freed.

The warning wants to tell you that you need to free s->x (not s.x)
later. This works for me:

#include <assert.h>
#include <stdlib.h>

typedef struct {
        char* x;
} struct_t;

int main(void)
{
        struct_t* s;

        s = malloc( sizeof(struct_t) );
        assert(s != NULL);
        s->x = malloc(10);

        /* ... */

        free(s->x);
        free(s);

        return 0;
}

Roland


More information about the splint-discuss mailing list