I know I should be using realloc to grow an array but in a momentary lapse of thought I did it this way. I realize the approach is wrong as I am corrupting the heap by growing it without allocating the array. So I am essentially writing garbage. But when the code is small and nothing else is happening I don't see why this should not work. I get garbage for the first few values
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **p = NULL;
int i=0;
int size = 5;
int *n = NULL;
p = malloc(sizeof(int*));
printf("p = %p \n", p);
for( i=0; i < size; i++ )
{
int *k;
k = malloc(sizeof(int));
*k = i;
p[i] = k;
printf("%p, %p, val = %d \n", k, p[i], *k);
}
printf("Now print the array -- \n");
for( i=0; i < size; i++ )
{
int *k;
k = p[i];
printf("value at mem %p == %d \n", p[i], *k);
}
printf("now print the next values in p \n");
for( i=0; i < size; i++ )
{
printf("value at %p = %p \n", p+i, *(p+i) );
}
return 0;
}
Here is the output of the code --
p = 0x7f8ffbc031c0
0x7f8ffbc031d0, 0x7f8ffbc031d0, val = 0
0x7f8ffbc031e0, 0x7f8ffbc031e0, val = 1
0x7f8ffbc031f0, 0x7f8ffbc031f0, val = 2
0x7f8ffbc03200, 0x7f8ffbc03200, val = 3
0x7f8ffbc03210, 0x7f8ffbc03210, val = 4
Now print the array --
value at mem 0x7f8ffbc031d0 == -71290384
value at mem 0x7f8ffbc031e0 == -71290352
value at mem 0x7f8ffbc031f0 == 2
value at mem 0x7f8ffbc03200 == 3
value at mem 0x7f8ffbc03210 == 4
now print the next values in p
value at 0x7f8ffbc031c0 = 0x7f8ffbc031d0
value at 0x7f8ffbc031c8 = 0x7f8ffbc031e0
value at 0x7f8ffbc031d0 = 0x7f8ffbc031f0
value at 0x7f8ffbc031d8 = 0x7f8ffbc03200
value at 0x7f8ffbc031e0 = 0x7f8ffbc03210
I cannot explain why the first two values are garbage even though the memory address pointed to by p and p+1 are what I put there.
p[2]and*p[0]have the same address - the third pointer overwrote the first number. Same forp[4]and*p[1].p = malloc(sizeof(int*));only allocates memory for oneint*but the laterp[i] = k;breaks it.