views:

268

answers:

1
char *p = new char[200];
char *p1 = p;
char *p2 = &p[100];
delete [] p1;

Btw this is not a test or anything i actually need to know this :)

+11  A: 
 // allocate memory for 200 chars
 // p points to the begining of that 
 // block
 char *p = new char[200];
 // we don't know if allocation succeeded or not
 // no null-check or exception handling

 // **Update:** Mark. Or you use std::no_throw or set_new_handler. 
 // what happens next is not guranteed

 // p1 now points to the same location as p
 char *p1 = p;

 // another pointer to char which points to the
 // 100th character of the array, note that
 // this can be treated as a pointer to an array
 // for the remaining 100-odd elements
 char *p2 = &p[100];

 // free the memory for 200 chars
 delete [] p1;

 // **Update:** Doug. T
 // [...] p and p2 are now pointing to freed memory 
 // and accessing it will be undefined behavior 
 // depending on the executing environment.
dirkgently
thx this answers my question, but is there any way to only delete the first 100 ?
Michael
You can reallocate - the normal method would be to allocate a new block of 100 bytes in size and then copy the second 100 bytes into that
1800 INFORMATION
No, you cannot have partitioned deletion. You have to make a second new call, copy out the part you want to save and delete the original.
dirkgently
ok thx for the answers guys
Michael
@dirkgently: your second comment is not correct - if allocation failed an exception would be thrown this means that the second line is only executed if allocation had succeeded. You do not need to check for null
1800 INFORMATION
That's what I said, I think: that what happens next is not guranteed.
dirkgently
You also said "no null-check"
1800 INFORMATION
So? If you have disabled exceptions, you need the null check. I pointed out both methods of error checking. And proceeded to explain the rest 'assuming things went well'.
dirkgently
How do you disable exceptions for failed new?
1800 INFORMATION
You disable exceptions before compiling. Since I don't know the compiler options I mentioned both. I am failing to see the merit of this discussion.
dirkgently
Or you use std::no_throw or set_new_handler. It's not normal to disable exceptions, so failure would usually terminate the program. So it *could* fall through because it's not specified, and it would be best to clarify that. Also, p and p2 cannot be used after the final line (not always obvious).
Mark
Nice answer. You may wish to add that p and p2 are now pointing to freed memory and accessing it will be undefined behavior depending on the executing environment.
Doug T.
Yes, I thought about that, but since decided against. Hnag on -- I'll update my post in a while with all the comments.
dirkgently
This line: char *p = new char[200]; Always, I mean ALWAYS returns a valid pointer. There is not need to check for NULL. If it fails an exception will be thrown and you will never get to the next line.
Martin York