Frage

I want to have a pointer to a randomly generated data with a certain size.

I don't know what happens when you do If I do char* data = new char[fileSize] or char* data = (char*)malloc(fileSize). I don't know if it initiates the allocated memory randomly or if all the bytes have the same value(or are zeroed).

Does new or malloc do the job or do I need something else?

War es hilfreich?

Lösung 4

Per the language specification, no new and malloc do not initialize data on primitive types. The compiler/runtime is free to give you memory it hasn't done anything with.

However in practice, the memory you allocate is quite probably zero'd out by the kernel. Modern operating systems do this as a security measure, not zeroing out memory that was once owned by another process could leak that other processes' data into your memory space. What if that other process had stored a password? Note this is not always true, and shouldn't be relied on. Always initialize your memory.

If you actually want random data, you need to generate it yourself. What random source you pull from is dependent on your needs. If you need some "random" data for testing, or for say, generating monsters in a game, use one of the pseudo-random generators available in the standard library to generate your data. If you need cryptographically secure number generation, it's a bit more complicated to be sure you have correct.

Andere Tipps

Your calls to new and malloc do not initialize the data they return. You'll get whatever values happen to be at the memory address allocated to you.

You're better off using std::vector:

std::vector<char> data(fileSize);

It will initialize the data to '\0' for you, and will take care of freeing up the underlying buffer memory for you when the vector goes out of scope.

both only allocate memory. As for the "C" method you could either use memset or allocate it directly with calloc(which sets it to 0). if allocated with new you have to zero it

Both allocates memory but when you use malloc to allocate memory for class object in c++ it not call constructor of a class but when you use new operator then it also calls constructor of a class that is one of the major difference between malloc and new .

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top