Skip to content

Commit

Permalink
Fix realloc(3) error handling
Browse files Browse the repository at this point in the history
From realloc(3) manpage:
       The realloc() function returns a pointer to the newly allocated memory,
       which  is  suitably  aligned for any built-in type and may be different
       from ptr, or NULL if the request fails.  If size was equal to 0, either
       NULL  or  a  pointer  suitable  to be passed to free() is returned.  If
       realloc() fails, the original block is left untouched; it is not  freed
       or moved.

If realloc() fails then the memory that was previously allocated needs
to be freed, or it will create a memory leak.

It was not a real problem because if realloc(3) failed then pcscd would
exit immediatly and the memory would not leak for a long time.

Thanks to PA193 project
https://github.com/vegaMato/PCSC-lite-project-tasks
  • Loading branch information
St4lkerino authored and LudovicRousseau committed Jan 14, 2019
1 parent ad8c6fb commit 4300438
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
8 changes: 6 additions & 2 deletions src/hotplug_libudev.c
Original file line number Diff line number Diff line change
Expand Up @@ -228,15 +228,19 @@ static LONG HPReadBundleValues(void)
Log2(PCSC_LOG_INFO,
"Increase driverTracker to %d entries", driverSize);
#endif
driverTracker = realloc(driverTracker,

void* tmp = realloc(driverTracker,
driverSize * sizeof(*driverTracker));
if (NULL == driverTracker)

if (NULL == tmp)
{
free(driverTracker);
Log1(PCSC_LOG_CRITICAL, "Not enough memory");
driverSize = -1;
(void)closedir(hpDir);
return -1;
}
driverTracker = tmp;

/* clean the newly allocated entries */
for (i=driverSize-DRIVER_TRACKER_SIZE_STEP; i<driverSize; i++)
Expand Down
6 changes: 4 additions & 2 deletions src/hotplug_libusb.c
Original file line number Diff line number Diff line change
Expand Up @@ -234,15 +234,17 @@ static LONG HPReadBundleValues(void)
Log2(PCSC_LOG_INFO,
"Increase driverTracker to %d entries", driverSize);
#endif
driverTracker = realloc(driverTracker,
void* tmp = realloc(driverTracker,
driverSize * sizeof(*driverTracker));
if (NULL == driverTracker)
if (NULL == tmp)
{
free(driverTracker);
Log1(PCSC_LOG_CRITICAL, "Not enough memory");
driverSize = -1;
closedir(hpDir);
return -1;
}
driverTracker = tmp;

/* clean the newly allocated entries */
for (i=driverSize-DRIVER_TRACKER_SIZE_STEP; i<driverSize; i++)
Expand Down

0 comments on commit 4300438

Please sign in to comment.