Roshan Nayak
Roshan Nayak

Reputation: 53

Deleting a pointer which contains a pointer pointing to another location

Recently while I was writing code for Stack implementation. I came across this doubt. Please help me get through this. The code is written as shown below.

struct Stack{
  int top;
  int capacity;
  int *array;
}

Stack* createStack(int capacity){
  Stack *S = new Stack;

  S->capacity = capacity;
  S->top = -1;
  S->array = new int[capacity];

  return S;
}

void Delete(Stack *S){
  delete S->array;
  delete S;
}

Now my doubt lies here in the delete function. As we can see that the S is pointing to a memory block of type Stack. Inside which there is another pointer pointing to an array of blocks of type int. What would happen when the S block is deleted directly without deleting the array block?

Upvotes: 0

Views: 101

Answers (1)

eerorika
eerorika

Reputation: 238351

What would happen when is delete the S block directly without deleting the array block?

The S object would be destroyed and that memory would be released. Nothing else would happen. In particular, the memory pointed by array would not be released. If the member was the only pointer to that memory, then it will be impossible to release it. This is called a memory leak.

P.S. Behaviour of the program is undefined if delete is used on a pointer that was not returned by new. In the example program, delete is used on a pointer returned by new[]. The behaviour of the program is undefined. delete[] must be used instead.

Upvotes: 3

Related Questions