Search code examples
cpointersmallocpointer-arithmeticpointer-to-pointer

Pointer arithmetic is working but pointer de-referencing is not working


I am trying to use pointer arithmetic to access pointer locations like an array. For testing same I wrote below code.

Now, I can see that pointer arithmetic is working because I can see incremented pointer address getting printed. But when I am de-referencing that pointer location to set some value then it is not working.

With my knowledge on C and pointers till now, I am not able to reason why pointer de-referencing is not working. If I was not able to get the increased the pointer location/address then atleast I would have understood that pointer arithmetic is not working, but when it is working then why pointer de-referencing is not working.

Code:

#include<stdio.h>
#include<stdlib.h>

int **DoublePtr;

void doublePointerTest();

int main(void)
{
    doublePointerTest();
}

void doublePointerTest()
{
    DoublePtr = malloc(sizeof(int*));
    *DoublePtr = malloc(sizeof(int) * 10);

    printf("Address of DoublePtr = %p\n", DoublePtr);
    printf("Address of *DoublePtr = %p\n", *DoublePtr);

    **DoublePtr = 100;

    *DoublePtr += 1;
    printf("+1 Address of *DoublePtr = %p\n", *DoublePtr);
    **DoublePtr = 1;

    *(*DoublePtr += 1) = 2;
    printf("+2 Address of *DoublePtr = %p\n", *DoublePtr);
    //**DoublePtr = 2;

    *DoublePtr += 1;
    printf("+3 Address of *DoublePtr = %p\n", *DoublePtr);
    **DoublePtr = 3;

   // *DoublePtr[4] = 4;
   // *DoublePtr[8] = 8;
   // *DoublePtr[3] = 3;
   // *DoublePtr[2] = 2;

    for(int i = 0; i < 10; i++, *DoublePtr += 1)
    {
        printf("%d.  ", i);
        printf("%d\n", **DoublePtr);
    }
}

O/P:

jharvard@appliance (~/psets/pset5/pset5_working): clang testing.c -o testing
jharvard@appliance (~/psets/pset5/pset5_working): ./testing 
Address of DoublePtr = 0x8cd4008
Address of *DoublePtr = 0x8cd4018
+1 Address of *DoublePtr = 0x8cd401c
+2 Address of *DoublePtr = 0x8cd4020
+3 Address of *DoublePtr = 0x8cd4024
0.  3
1.  0
2.  0
3.  0
4.  0
5.  0
6.  0
7.  0
8.  135105
9.  0
jharvard@appliance (~/psets/pset5/pset5_working):


Updates:

As per comments and answer, corrected my code from DoublePtr = malloc(sizeof(int)); to DoublePtr = malloc(sizeof(int*)); and tested but it gives same result.


Solution

  • Your code writes 100,1,2,3 to the first 4 locations of the 10 you malloc.

    Then you print out the contents of the next 10 locations starting from the 3: you see the 3, then 6 uninitialized values, and then a buffer overflow.

    You never print the values of the first 3 locations. Your dereferencing to set the value is working but you never output the result.

    Perhaps you meant to set *DoublePtr back to its original value before printing?