write and read string to binary file C++

To write a std::string to a binary file, you need to save the string length first: std::string str(“whatever”); size_t size=str.size(); outfile.write(&size,sizeof(size)); outfile.write(&str[0],size); To read it in, reverse the process, resizing the string first so you will have enough space: std::string str; size_t size; infile.read(&size, sizeof(size)); str.resize(size); infile.read(&str[0], size); Because strings have a variable size, unless … Read more

How big can a malloc be in C?

Observations Assuming a typical allocator, such as the one glibc uses, there are some observations: Whether or not the memory is actually used, the region must be reserved contiguously in virtual memory. The largest free contiguous regions depends on the memory usage of existing memory regions, and the availability of those regions to malloc. The … Read more

Use of cudamalloc(). Why the double pointer?

All CUDA API functions return an error code (or cudaSuccess if no error occured). All other parameters are passed by reference. However, in plain C you cannot have references, that’s why you have to pass an address of the variable that you want the return information to be stored. Since you are returning a pointer, … Read more

Do I really need malloc?

TL;DR If you don’t know what you’re doing, use malloc or a fixed size array in all situations. VLA:s are not necessary at all. And do note that VLA:s cannot be static nor global. Do I really need to use malloc here? Yes. You’re reading a file. They are typically way bigger than what’s suitable … Read more