0

I have the following C++ code:

int main(){
    unsigned char *abc = (unsigned char *)calloc(100,1);
    unsigned char *def = &abc[50];
    delete def;
}

Would this deallocate all the memory allocated by the call to calloc, or just the memory starting at the memory location where def points to?

1
  • What unsigned char *def = &abc[50]; does is that, the def pointer is only making a reference to where the pointer *abc at position abc[50] is pointing to. def should be pointing at the element in that location however it`s empty at the moment. Commented Aug 14, 2014 at 4:08

4 Answers 4

4

It is undefined behavior. A crash, if you are lucky.

According to C++ standard (Working Draft, N3291=11-0061)

3.7.4.2 Deallocation functions [basic.stc.dynamic.deallocation]

...

The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. Otherwise, the behavior is undefined if the value supplied to operator delete(void*) in the standard library is not one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, constvstd::nothrow_t&) in the standard library ...

There are several problems here. First, you should use free if you used calloc.

Then, you should pass to free the same pointer you got from calloc.

calloc allocates memory as one continuous block, and the entire block gets deallocated with free, not a part of it.

See http://www.cplusplus.com/reference/cstdlib/calloc/.

Sign up to request clarification or add additional context in comments.

Comments

3

delete can only delete memory allocated with new.

for memory allocated with calloc deallocate it using free.

and no, you can't just use a pointer to somewhere inside the allocated memory.


in C++, deal with simple character strings by using std::string from the <string> header.

it takes care of memory management for you.

Comments

1

It wouldn't necessarily deallocate anything as it has undefined behavior. You can only call delete on a pointer which was allocated with new. Not only was the memory allocated with calloc instead of new, but you are also not passing a pointer to what calloc returned, but to some other position within that block of memory.

Comments

0

Isn't *abc undefined there? delete def; wouldn't do anything if there is nothing to delete!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.