Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ymdatta opened this issue Oct 29, 2024 · 0 comments
Open

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

ymdatta opened this issue Oct 29, 2024 · 0 comments

Comments

@ymdatta
Copy link

ymdatta commented Oct 29, 2024

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.

ymdatta added a commit to ymdatta/shapelib that referenced this issue Oct 29, 2024
ymdatta added a commit to ymdatta/shapelib that referenced this issue Oct 29, 2024
ymdatta added a commit to ymdatta/shapelib that referenced this issue Nov 1, 2024
ymdatta added a commit to ymdatta/shapelib that referenced this issue Nov 1, 2024
ymdatta added a commit to ymdatta/shapelib that referenced this issue Nov 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant