Friday, September 2, 2016

Double Pointer (Pointer to Pointer) some input

A double pointer has two basic meanings.
        One is of a pointer to a pointer, where changing the value of double pointer will result in the original pointer being changed.
        Another is that of a two-dimensional array, such as a matrix

Example for Two dimensional array
int main( int argc, char **argv (or) char* argv[] )
{
// print the first string
printf("%s\n", argv[0]);

return 0;
}

The other example where the double pointer is a pointer to a pointer, lets say you have a function foo() that allocates memory for a pointer that was declared in function main()

void foo( char ** ptr)
{
*ptr = malloc(255); // allocate some memory
strcpy( *ptr, "Hello World");
}

int main()
{
char *ptr = 0;
// call function with a pointer to pointer
foo( &ptr );
printf("%s\n", ptr);
// free up the memory
free(ptr);

return 0;
}

Creating 2D int array
//Create your pointer
int **ptr;
//Assign first dimension
ptr = new int*[5];
//Assign second dimension
for(int i = 0; i < 5; i++)
ptr[i] = new int[5];
Deleting 2D array
for (int x = 0; x < nCol; ++x)
delete [] ptr[x];
delete [] ptr;

How delete[] knows how many items to be destroyed ??
 When an array is created with new[], the size of array is stored in the metadata at the memory block. delete[] makes use of that information.

New[] operator requires default constructor  , for ex
   student* kar = new student[10](34,"");  // its completely wrong
  student * kar = new student[10];   // Correct

new & delete are based on malloc & free. Malloc additionally allocate a header storing the size allocated, so free() knows the size to free. new[] not only keeps the malloc header, but also has an extra header storing the size of the array/vector, so delete[] knows how many objects are in the array/vector, and thus knows how many times to call the destructor.


Allocation Using
Deallocation using
Result
Remarks
new
delete
Ok

new[]
delete[]
Ok

new
delete[]
The vector delete will try to delete more objects depending on the random value it gets from its object-count location and will obviously result in heap corruption.
Compiler will not track the Pointer, Its developer responsibility to call the respective delete operator (ie delete or delete[])
new[]
delete
Memory leak
It will delete only first item in the array

No comments:

Post a Comment