Menu

#118 string.cpp memleak or segfault

closed
other (34)
1
2016-12-11
2004-12-11
No

The routine below needs to return a value on failure and the
routines which call it need to be able to deal with the potential
failure, otherwise you have:
- a memleak/segfault if malloc fails
- a memleak/segfault/unfreed memory if realloc fails.

void String::reserve_i(size_t s)
{
size_t old_size = end_ - begin_;
size_t new_size = (storage_end_ - begin_) * 3 / 2;
if (new_size < 64) new_size = 64;
if (new_size < s + 1) new_size = s + 1;
if (old_size == 0) {
if (begin_) free(begin_);
begin_ = (char *)malloc(new_size);
} else {
begin_ = (char *)realloc(begin_, new_size);
****if this is NULL then you have lost your pointer to an existing
block of unfreed memory
}
*****if begin_ == NULL then you have error****
end_ = begin_ + old_size;
storage_end_ = begin_ + new_size;
}

This a non-tested example, but a possible direction to go:
bool String::reserve_i(size_t s)
{
size_t tmp = begin_;
size_t old_size = end_ - begin_;
size_t new_size = (storage_end_ - begin_) * 3 / 2;
if (new_size < 64) new_size = 64;
if (new_size < s + 1) new_size = s + 1;
if (old_size == 0) {
if (begin_) free(begin_);
tmp = begin_ = (char *)malloc(new_size);
} else {
tmp = (char *)realloc(begin_, new_size);
if (tmp) begin_ = tmp; else free(begin_);
}
end_ = begin_ + old_size;
storage_end_ = begin_ + new_size;
return (tmp != 0);
}

Discussion

  • Kevin Atkinson

    Kevin Atkinson - 2004-12-11

    Logged In: YES
    user_id=6591

    My program will crash in a lot of places if malloc or
    realloc fails. I don't worry about it because if you are
    out of memory Aspell crashing is the least of your problems.

     
  • Kevin Atkinson

    Kevin Atkinson - 2004-12-11
    • priority: 5 --> 1
    • assigned_to: nobody --> kevina
    • status: open --> open-wont-fix
     
  • Kevin Atkinson

    Kevin Atkinson - 2006-11-18
    • labels: --> other
     
  • Kevin Atkinson

    Kevin Atkinson - 2016-12-11

    This issue has moved to GitHub: https://github.com/GNUAspell/aspell/issues/189

     
  • Kevin Atkinson

    Kevin Atkinson - 2016-12-11
    • Status: open-wont-fix --> closed
     
MongoDB Logo MongoDB