mirror of
https://github.com/opencv/opencv.git
synced 2025-06-09 02:23:23 +08:00
Fix memory leak and handle realloc failure
In the previous code, there was a memory leak issue where the previously allocated memory was not freed upon a failed realloc operation. This commit addresses the problem by releasing the old memory before setting the pointer to NULL in case of a realloc failure. This ensures that memory is properly managed and avoids potential memory leaks.
This commit is contained in:
parent
157b0e7760
commit
e16ca08b33
@ -375,15 +375,21 @@ static long THDiskFile_readString(THFile *self, const char *format, char **str_)
|
|||||||
long total = TBRS_BSZ;
|
long total = TBRS_BSZ;
|
||||||
long pos = 0L;
|
long pos = 0L;
|
||||||
|
|
||||||
|
if (p == NULL)
|
||||||
|
THError("read error: failed to allocate buffer");
|
||||||
for (;;)
|
for (;;)
|
||||||
{
|
{
|
||||||
if(total-pos == 0) /* we need more space! */
|
if(total-pos == 0) /* we need more space! */
|
||||||
{
|
{
|
||||||
total += TBRS_BSZ;
|
total += TBRS_BSZ;
|
||||||
p = (char*)THRealloc(p, total);
|
char *new_p = (char*)THRealloc(p, total);
|
||||||
|
if (new_p == NULL)
|
||||||
|
{
|
||||||
|
THFree(p);
|
||||||
|
THError("read error: failed to reallocate buffer");
|
||||||
|
}
|
||||||
|
p = new_p;
|
||||||
}
|
}
|
||||||
if (p == NULL)
|
|
||||||
THError("read error: failed to allocate buffer");
|
|
||||||
pos += fread(p+pos, 1, total-pos, dfself->handle);
|
pos += fread(p+pos, 1, total-pos, dfself->handle);
|
||||||
if (pos < total) /* eof? */
|
if (pos < total) /* eof? */
|
||||||
{
|
{
|
||||||
@ -409,15 +415,21 @@ static long THDiskFile_readString(THFile *self, const char *format, char **str_)
|
|||||||
long pos = 0L;
|
long pos = 0L;
|
||||||
long size;
|
long size;
|
||||||
|
|
||||||
|
if (p == NULL)
|
||||||
|
THError("read error: failed to allocate buffer");
|
||||||
for (;;)
|
for (;;)
|
||||||
{
|
{
|
||||||
if(total-pos <= 1) /* we can only write '\0' in there! */
|
if(total-pos <= 1) /* we can only write '\0' in there! */
|
||||||
{
|
{
|
||||||
total += TBRS_BSZ;
|
total += TBRS_BSZ;
|
||||||
p = (char*)THRealloc(p, total);
|
char *new_p = (char*)THRealloc(p, total);
|
||||||
|
if (new_p == NULL)
|
||||||
|
{
|
||||||
|
THFree(p);
|
||||||
|
THError("read error: failed to reallocate buffer");
|
||||||
|
}
|
||||||
|
p = new_p;
|
||||||
}
|
}
|
||||||
if (p == NULL)
|
|
||||||
THError("read error: failed to allocate buffer");
|
|
||||||
if (fgets(p+pos, total-pos, dfself->handle) == NULL) /* eof? */
|
if (fgets(p+pos, total-pos, dfself->handle) == NULL) /* eof? */
|
||||||
{
|
{
|
||||||
if(pos == 0L)
|
if(pos == 0L)
|
||||||
|
Loading…
Reference in New Issue
Block a user