I use buf2 because I can't read() directly into a uint8_t. If I try to cast it as a char, I get an error about losing precision. |
At worst you'd get a warning. You wouldn't get an error unless you're casting improperly.
This will work just fine, and is what I recommend:
|
infile.read( reinterpret_cast<char*>(buf), siz );
|
Also, read() only accepts a pointer. |
Right, but the pointer you give it has to actually point to something.
I'm reading from infile into buf2, so shouldn't it allocate memory automatically? |
Nope.
Or should I malloc some space? |
Don't use malloc in C++. Use new[] if you have to.
That's one option, but again it's pointless here because you could just read to buf directly.
Pointers and buffers are two different things. A buffer is actual allocated space in memory that can hold data. A pointer is just an address. Often times, a pointer points to the first byte of a buffer:
1 2 3
|
uint8_t abuffer[100]; // a buffer of 100 uint8_t's
uint8_t* ptr = abuffer; // a pointer that points to the first uint8_t of that buffer
|
Functions like read() expect the pointer you give them to be pointing to a buffer. That way the data they read goes into that buffer.
You're not giving it any buffer. You're just giving it some random address because you never initialized your pointer. So read() is just taking the data and putting it wherever, which is very dangerous (and is what was causing the program to crash)
Also, the last part is just making sure that buf2 exists so I don't tell the program it copied successfully when it didn't. |
That doesn't really make sense though. You're checking to see if buf2 is null, but you never set buf2 to anything. That'd be like doing this:
1 2 3 4 5 6
|
int apples;
if(apples == 5)
{
cout << "we have 5 apples";
}
|
Will that if() statement be true? Who knows! You never say how many apples there are, so how can you expect the if() statement to have any significance?
EDIT:
Anyways, I know cout is messing something up since it works fine without it... for about 10 calls. :( |
NO, cout has absolutely nothing to do with it
Trust me. It's heap corruption. Heap corruption makes your program do all sorts of crazy, unpredictable things.