Prabhu
Prabhu

Reputation: 717

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

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?

Upvotes: 4

Views: 599

Answers (3)

Polynomial
Polynomial

Reputation: 28326

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");
}

Upvotes: 5

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133092

C++ doesn't provide a mechanism for that. However, you could implement your own freestanding myresize function which would do something like this:

bool myresize(std::string& s, int newSize)
{
     if(newSize > maxSize)
       return false;
     s.resize(newSize);
     return true;
}

You could write similar functions for push_back, append, etc

Of course it should be your responsibility to call these functions rather than strings members.

Upvotes: 4

unwind
unwind

Reputation: 400029

For a character array, just do

char ten_k[10240];

It's not as if character arrays in C ever grow automatically, so I'm having a hard time seeing how this can be a problem for you.

In C++, you probably need to wrap a standard string type to implement the limit. This is often done as a template class, i.e. you'd have something like:

LimitedString<10240> ten_k;

Of course, this is a bit backwards; it'd make more sense to incorporate the limit to whatever code generates the string in the first place, since that code probably knows what to do when the limit is hit.

Upvotes: 4

Related Questions