how this code works

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • codelife
    New Member
    • Jul 2016
    • 1

    how this code works

    I'm workig on memory allocation and trying to understand this code.

    output prints
    i=0
    d=149909512 - How is d getting these numbers?
    *d=0,
    i=5, d[i]135145.
    how can d have these numbers if malloc returns the address of the beginning of allocated memory or NULL if it fails.

    Code:
    #include<stdio.h>
    
    int main(void)
    {
        int i, *d;
            /*printf("%d\n %d",i,*d);*/
        d =  malloc( 5 * sizeof(int) );
        printf("i=%d\n d=%d\n *d=%d\n",i,d,*d);
        
        for(i = 0; i < 5; i++)
        d[i] = i + 100;
        printf("i=%d\n d[i]%d",i,d[i]);
            
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The for loop exits with i == 5. When i is 4 the ++i has occurred before i < 5 is tested.

    I suggest a pair of braces around the loop so both the assignment and printf are inside the loop

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      You are using the "%d" format specifier to print the value of d. That format specifier should only be used with int arguments. Use "%p" for pointers.

      You should test the value of d and be careful not to dereference it if the value is NULL.

      Your first printf prints the value of *d before it has been initialized. The value of an uninitialized variable is unpredictable. You can avoid this problem by using calloc instead of malloc.

      Comment

      Working...