0

I have to below code which assigns memory using malloc:

typedef struct qu_n_t {
                  int    item; 
                  struct qu_n_t *next; 

               } qu_node_t;
qu_node_t *currentblock = NULL;
qu_node_t *tmp;
currentblock = (qu_node_t *) malloc( 5 * sizeof(qu_node_t) );
tmp = currentblock++;

Now once the code is executed, currentblock pointer will be assigned memory address of 5 * sizeof(qu_node_t) . If I use currentblock what will be the address assigned to it? Would it be the first block address from the 5 blocks assigned using malloc?

Arnold
  • 185
  • 1
  • 2
  • 8
  • Why do you use different tag- and typename-identifiers? Also, [Don't cast the result of malloc (and friends)](http://stackoverflow.com/q/605845). And sure, it points to the start of the block, which is yet indeterminate. – Deduplicator Feb 06 '15 at 18:14
  • 1
    Style suggestion. Pass malloc sizeof(*currentblock). The result is the same but it is clear during code review that sizeof() will return the right thing instead of having to lookup the type of the variable being assigned to. – Sam Feb 06 '15 at 18:18
  • 1
    @sam: you might as well also combine the definition with the `malloc` call too: `qu_node_t *currentblock = (qu_node_t *)malloc(5 * sizeof(*currentblock));` where the cast is up for debate too (I'm not as averse to it as some people are, but there are conditions that must be met). – Jonathan Leffler Feb 06 '15 at 18:26
  • Absolutely. This gives static analyzers a chance to catch errors. Love it. Do it. – Sam Feb 08 '15 at 23:38

2 Answers2

1

Yes, after the call to malloc, currentblock points to the first block in the array.

After the next line, tmp points to the first block and currentblock to the second.

1

Yes, it will be the address of the first block. Essentially you allocated an array of 5 elements of struct qu_n_t. So you can access the second element using currentblock[1], etc.

Igor Popov
  • 2,588
  • 17
  • 20