Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit an array to a particular size (in kilobytes)

Tags:

c++

c

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?

like image 540
Prabhu Avatar asked Dec 12 '22 06:12

Prabhu


1 Answers

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");
}
like image 72
Polynomial Avatar answered Dec 27 '22 18:12

Polynomial