Skip to content

dbfopen: possible memory leak with realloc when allocation fails #165

@ymdatta

Description

@ymdatta

What is the bug?

While working on GRASS GIS I found some possible memory leak issues with the shape library, which is external to GRASS GIS, and imported from GDAL.

This was found using cppcheck static analysis tool.

An example scenario (dbfopen.c#L462):

pabyBuf = STATIC_CAST(unsigned char *, realloc(pabyBuf, nHeadLen));

When realloc returns NULL for example in cases where there is not enough memory, we overwrite pabyBuf pointer to NULL, thus losing access to the memory previously pointed by the pabyBuf and not freeing it, which causes memory leak. (In a successful scenario, realloc automatically frees the memory pointed to pabyBuf if its returning a different pointer)

There are multiple realloc scenarios in the dbfopen.c which fall under same error category, though are not detected by cppcheck directly.

The solution I believe should be using a temporary pointer to store the address to pointer after reallocation and only if it's not NULL, assign it back.

pabyBuf_t = STATIC_CAST(unsigned char *, realloc(pabyBuf, nHeadLen));
if (pabyBuf_t == NULL) {
    free(pabyBuf);
    // raise appropriate error
} else {
    pabyBuf = pabyBuf_t;
}

Steps to reproduce the issue

  1. Install cppcheck.

    I have used version 2.7

  2. Run dbfopen.c

Should be independent of architecture and reproducible on all platforms.

Versions and provenance

I have checked latest development version with the cppcheck tool and observed the issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions