Buffer size using a parameter

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 ?

Thank you for your help :)
Last edited on
1
2
3
4
5
6
7
8
9
#include <string>

void Example (int size)
{
    std::string buffer( size, ' ' );
    
    for(int i = 0; i < size; i++)
    {}    // do something in my buffer 
}
Thank you lastchance for your answer.

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
inline char 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));
}
Last edited on
1
2
3
4
5
6
7
8
9
void Example (int size)
{
    char *buffer = new char[size];
    
    for(int i = 0; i < size; i++)
    {}    // do something in my buffer
    
    delete [] buffer;
}




but in my code I have to use Char which are computed using another function

????
Last edited on
Ok, now it works as expected, but what is the best way to dynamically set my buffer size ?

char* buffer = { (char*)_malloca(sizeof(char) * (size)) };
or
char *buffer = new char[size];
It depends what language do you use?
malloc is for C
new is for C++
c++
The first one generates an heap overflow at the end of the main process :/
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!"
Well. I understand. Thank you everyone for your good explanations which are always clever, relevant and useful for me. I wish you the best ++
A possible rewrite of the OP function using a C++ string (with some output to see what is happening):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

void Example(size_t);

int main()
{
   Example(60);
}

void Example(size_t SIZE)
{
   std::string str1;  // create an empty string

   str1.resize(SIZE); // and resize it after-the-fact

   std::string str2(SIZE, 'A');  // or size on creation and fill

   for (size_t itr { 0 }; itr < str1.size(); ++itr)
   {
      str1[itr] = 'A' + itr;
   }

   std::cout << str1 << '\n';
}
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|
in my code I have to use Char which are computed using another function
1
2
3
4
5
6
7
8
#include <iostream>
#include <string>

int main() {
  std::string array = "Hello"; // assert: array.size() > 4
  array[4] = ' '; // pretend that the whitespace char comes from "another function"
  std::cout << array;
}

It looks totally possible to store char in an "element" of string.
but what is the best way to dynamically set my buffer size


In C++ in this context, probably std::unique_ptr if you don't want to use std::string/std::vector et al

http://www.cplusplus.com/reference/memory/unique_ptr/

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) {
	const auto buffer { std::make_unique<char[]>(10)};

	for (size_t i {}; i < size; ++i) {
		// do something in my buffer
	}
}


Last edited on
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
True, but how much is the initialization cost of char?
If buffer is going to be initialized after allocation, then from C++20 there is std::make_unique_for_overwrite which can be much faster.

https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique
Topic archived. No new replies allowed.