0

What's the difference between

buf = (char*)std::malloc(aSize * sizeof(float));

and

buf = new char[aSize * sizeof(float)];

I have seen both used, and I usually use the first. However today I noticed that the second one has started sometimes throwing std::bad_alloc and crashing. Changing it to the first fixed the issue.

What exactly does each line do?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jagoly
  • 939
  • 1
  • 8
  • 32
  • I removed the `c` tag, since C doesn't have `new`. – Barmar Nov 02 '14 at 08:51
  • 1
    Neither approach has a place in C++ and you are better off using `std::vector` in the first place. If you actually mean to allocate `float` objects in C++ you'd use `new float[aSize]`. – Dietmar Kühl Nov 02 '14 at 08:51
  • 2
    *"Changing it to the first fixed the issue."* -- It almost certainly didn't. In all likelihood, it just shifted the latent problem elsewhere. – NPE Nov 02 '14 at 08:52
  • Well, I'm loading in binary files, so I'm not sure how I would use a vector for that. – Jagoly Nov 02 '14 at 08:54
  • @Jagoly, In the worst case, same way you'd use your pointer. – chris Nov 02 '14 at 08:56
  • @DietmarKühl The first statement is false, it most certainly does have a place (so we should just abandon any form of networking or buffer mechanism?) but I agree that in this case. An `std::vector` would probably be better suited. – RamblingMad Nov 02 '14 at 08:56
  • @CoffeeandCode: The reason you'd not use `malloc()` is that it can't be replaced while you can replace the C++ operator. However, you'd also not use `new char[...]` to allocate raw memory. If you really mean to allocate raw bytes you'd use `operator new()` or `operator new[]()`. So, how the statement wrong that you wouldn't use either of the approaches in original question? – Dietmar Kühl Nov 02 '14 at 09:00
  • @Jagoly Then it sounds like you need to learn how to use vectors. – David Schwartz Nov 02 '14 at 09:01
  • @DavidSchwartz I don't suppose you can give an example of how I should use a vector to load a binary file? The file contains more than just floats. All of the examples I can find use raw pointers. should I not be using fstream.read? – Jagoly Nov 02 '14 at 09:13
  • @Jagoly Well, you can use a `std::vector` for representation of raw binary data. I'm using it all the time for this purpose. – πάντα ῥεῖ Nov 02 '14 at 09:23
  • @πάνταῥεῖ I'm still not sure what to do with that though. Wouldn't I have to resize the vector before hand, and use fstream.read(vec.data()...) anyway? Upon reading what I just wrote, that sounds like exactly what I should do. Then I don't need worry about sizing the pointer or cleaning it up. Am I correct? Thanks :) – Jagoly Nov 02 '14 at 09:37

0 Answers0