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);
}
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.
This issue has moved to GitHub: https://github.com/GNUAspell/aspell/issues/189