Search code examples
cpointersmallocdynamic-memory-allocationcs50

How is memory allocated in c , and why diffrence between two contiguous is always 4?


#include <stdio.h>
#include <cs50.h>

int main (void)
{
    int *x;
    x = malloc(sizeof(long long)*3);
    scanf("%i %i %i",x, (x+1), (x+2));
    printf("%i\t %i\t %i\n",(int)x, (int)(x+1), (int)(x+2));
    printf("%i\t %i\t %i\n",*x, *(x+1), *(x+2));
    free(x);
}

The output of this program for input 12,2,3 is :

43171856         43171860        43171864
12       2       3

so, my question is why difference between address is 4 in each case , and if *x points to 43171856 then *(x+1) should point to 4317185 not 43171860? sizeof(long long) is also 8 bytes , so how allocated memory allocates 8 bytes between those 4 bytes between 43171856 and 43171860.


Solution

  • This is one of the really confusing bits of C: x+1, when x has a pointer type, increments the numeric value of x by sizeof(*x), not by 1.

    It has to be that way, because, for any pointer type T *x, x+1 is the same as &x[1]. &x[1] is the address of the second T in the pseudo-array pointed to by x. Therefore the numeric value of x+1 must be equal to the numeric value of x plus sizeof(T), which in your case is 4.

    malloc, meanwhile, doesn't know that you passed it 3*sizeof(long long). It sees malloc(24) and it gives you 24 bytes, which (on your platform) is six ints. You are using only the first three, which is fine, it just wastes a little memory. You probably meant to write 3*sizeof(int).