Hello everyone. Is there a way to set a buffer size using a function argument? I don't understand why it is not possible. I guess that it is a way to avoid buffer overflow, but I would like to define a buffer size inside a function according one of these parameters.
1 2 3 4 5 6 7 8
void Example (int size)
{
char buffer[size]; // generates an error "constant expected"
// char buffer[512]; // this one works
for (DWORD t = 0; t < sizeof(buffer); t++)
buffer[t] = static_cast<char>(doSomethingAt(t));
}
I found a way in order to set a buffer size :
char* buffer = { (char*)_malloca(sizeof(char) * (size)) };
But in this case, it seems to me that I cannot "do something" in this buffer...
Perhaps I have to change something in my loop using t index ?
Yes. I know that I could simplify code using a string, but in my code I have to use Char which are computed using another function - more or less like in this example :
1 2 3 4 5 6 7 8 9 10
inlinechar doSomethingAt(int t) { return (t >> 2); }
void Example (int size)
{
char buffer[size]; // generates an error "constant expected"
// char buffer[512]; // this one works
for (DWORD t = 0; t < sizeof(buffer); t++)
buffer[t] = static_cast<char>(doSomethingAt(t));
}
If you are using C++ a C++ container like a std::string or std::vector is a whole lot better than the perils of manual memory management.
The less one has to deal with the nitty-gritty of dealing with the mechanics of memory management the better IMO. Making mistakes resulting in stomping on memory not owned or not properly releasing memory when finished is a common "ooops!"
With this you don't need to worry about delete as it is RAII based.
1 2 3 4 5 6 7 8 9
#include <memory>
void Example(size_t size) {
constauto buffer { std::make_unique<char[]>(10)};
for (size_t i {}; i < size; ++i) {
// do something in my buffer
}
}
but what is the best way to dynamically set my buffer size
Since the buffer is in this case an array of char, the "best", most specialized C++ solution is std::string, because string is an array of char with plenty of most convenient syntactic sugar. All that decoration/encapsulation aside an array of char is an array of char.
If you want to emphasize that the buffer is an array, i.e. do not need any string manipulation, then the next candidate is std::vector<char>.
The size of both is dynamic. You can still shoot yourself into foot with them if you want, but not as easily than with other methods.
One possible disadvantage of the C++ methods is that they will initialize the entire contents of the buffer. Depending on how often you're calling this function, that might be a performance penalty. If performance turns into a problem then you may need to fall back to to malloc/free