This happens to you because static data are stored in stack and its size is a few MB. If you allocate memory dynamically your data goes into heap and it is much bigger.
In your case I would use containers. Probably vector
.
std::vector<char> buffer(size);
Containers are safer then pointers and much safer then dynamically allocations because containers auto delete stuff if you don't use it anymore. Also you can always safely increase size of container just pushing another value.
If you need to pass it to function you can pass reference (it is probably the best option), however you can pass pointer to first element by doing this: &buffer[0]
(this works only with vector
).
What is more you can iterate through all containers by getting pointer to data.
for (std::vector::iterator it = buffer.begin(); it != buffer.end(); ++it)
{/*some stuff*/}
Iterations looks the same with any type of container.
What is more, you allocate 4348928 chars, it is about 4MB. But if you need to allocate lets say 300MB allocation with new
usually fails (the same with vector
). For such a big allocations you should use std::deque
.