By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,949 Members | 921 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,949 IT Pros & Developers. It's quick & easy.

how this code works

P: 1
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.

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2.  
  3. int main(void)
  4. {
  5.     int i, *d;
  6.         /*printf("%d\n %d",i,*d);*/
  7.     d =  malloc( 5 * sizeof(int) );
  8.     printf("i=%d\n d=%d\n *d=%d\n",i,d,*d);
  9.  
  10.     for(i = 0; i < 5; i++)
  11.     d[i] = i + 100;
  12.     printf("i=%d\n d[i]%d",i,d[i]);
  13.  
  14. }
  15.  
  16.  
Jul 12 '16 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
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
Jul 12 '16 #2

Expert 100+
P: 2,396
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.
Jul 15 '16 #3

Post your reply

Sign in to post your reply or Sign up for a free account.