Just do
char* only_valid_data = new char[data_size];
to allocate.
To free you do
delete[] only_valid_data;
Important note: When you allocate memory with new
it will allocate data_size
elements, not data_size
bytes (like malloc
does). The size of an element is the size of the non-pointer base type, in your case e.g. sizeof(*only_valid_data)
. In this case the element size and the byte size is the same (as sizeof(char)
is specified to always be 1
), but if the base type is something else it will make a big difference.
For example, if you do
int* int_ptr = new int[10];
then ten integers will be allocated, not ten bytes. This is equivalent to
int* int_ptr = reinterpret_cast<int*>(malloc(10 * sizeof(*int_ptr)));
Also note that for complex types, like structures and classes, allocating with new
(or new[]
) does more than just allocating memory, it will also make sure that the allocated object(s) constructor is called. The malloc
function only allocates memory, it doesn’t call the constructor.
Final note: The problem you have with the segmentation fault is probably not caused by your allocation, no matter how you allocate the memory. The problem is more likely because of something else, something you do not show in your question, like writing out of bounds of the allocated memory or dereferencing a null-pointer.
You need run your program in a debugger to catch the crash in action, it will allow you to examine the function call stack, and if the crash doesn’t happen in your code then you walk up the call stack until you reach your code. There you can examine the values of variables, to help you understand why the problem occurred.