如何将数组限制为特定大小(以千字节为单位)

Pra*_*bhu 4 c c++

在特定情况下,我需要有大小不应超过 10 kB 的变量(字符数组或 std:string)。

如何限制此变量的大小?

Pol*_*ial 5

只是不要将其调整为超过大小限制:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以这样使用它:

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");
}
Run Code Online (Sandbox Code Playgroud)