In a particular situation I need to have variable (character array or std:string) where the size should not be more than 10 kB.
How can I limit the size of this variable?
Just don't resize it to be more than the size limit:
char* realloc_lim(char* data, int new_count, bool &ok)
{
if(sizeof(char) * new_count > SIZE_LIMIT)
{
ok = false;
return null;
} else {
ok = true;
return (char*)realloc((void*)data, sizeof(char) * new_count);
}
}
You can use it like this:
bool allocation_ok = false;
int newsize = readint(); // read the size as an int from somewhere
buffer = realloc_lim(buffer, newsize, &allocation_ok);
if(!allocation_ok)
{
printf("Input size was too large!\n");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With