Read in more than memory allocated

Good day everyone!


char * l = new char[4];
//Creating pointer to a block of memory, length 4.

int length = 20;
file_content.read(l, length);

//telling the function to read in more than length 4.

Why doesn't the program crash, when I read in more than I have "reserverd"?





Last edited on
volang wrote:
Why doesn't the program crash, when I read in more than I have "reserverd"?


Luck.
Okey.

If my file contains for example 20 chars, should I allocate 20 chars, or 20 + 1. Read() doesn't add a terminating null, but something else might?
If it's just a char array no need to add anything beyond the 20.
If it's (later) to be a null-terminated C-string then add space for that.

Not all char arrays are destined to be C-strings.

Basically, it depends what you want to do with it. There's no harm in a little extra space (as I keep telling our office manager).
Last edited on
Luck.

So there is a chance that there is space available already even without "allocating memory"?

Only reason I use "new char [20], is to guarantee it?
Basically, it depends what you want to do with it. There's no harm in a little extra space (as I keep telling our office manager).


I like this. Better safe than sorry
So there is a chance that there is space available already even without "allocating memory"?


No, the "luck" refers to you not crashing. That space doesn't belong to your char array ... it could well belong to another variable. You could be unwittingly changing the value of that variable. It's like you taking up multiple seats on the train - hard to stop, but decidedly unpopular.
Last edited on
Got it.

But let's say i'm trying to allocate memory[200000]. (I'm guessing that the process of allocation is "one spot at a time"). While this is happening I catch an exception, and maybe some of the length was already allocated before the exception.

Should I delete the pointer here, or free it somehow?
If an exception occurs during a new, you have a guarantee that the memory will be released. You don't have to do anything.
volang wrote:
I'm guessing that the process of allocation is "one spot at a time"


No, you either get it in its entirety or you get nothing. It's just a starting position and a size for contiguous memory.

If the exception referred to unavailable memory then nothing will have been set.
If the exception referred to something else then the memory will already have been allocated to you.
Great!

Thanks alot, it's appreciated
Topic archived. No new replies allowed.