2

I have a piece of code where

for ( ; ; )
{

  char *buf;

  /* Some code */
}

The question here will the code allocate memory every time when it cycles through the loop . I mean atleast 4 bytes will be reserved for the pointer when it cycles .

4 Answers 4

8

Space for the pointer will be allocated on the stack, but it will be popped off at the end of every iteration, so you don't need to worry about it.

5

I think any reasonable compiler will optimize out the allocation. For example, take a look at the GCC-produced assembly:

_foo:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $40, %esp
L2:
    movl    -12(%ebp), %eax
    movl    %eax, (%esp)
    call    L_puts$stub
    jmp     L2
0

The char* will be reallocated for every iteration, yes, but it will also be freed before the next iteration, so at least this won't cause a memory leak (unless you use malloc without a free in that loop).

Anyway, you should put it out of the for-loop for performance reasons (although perhaps the compiler optimizes this and doesn't reallocate the memory for the pointer, but I wouldn't count on that).

1
  • that's micro-optimisation. let the compiler do that for you.
    – Alnitak
    Mar 12, 2009 at 8:49
0

What you possibly do need to worry about is the memory that buf is pointing to. You snipped out the code that actually uses buf, but if you use malloc() or similar to make a buffer, it won't be freed unless you also free() it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.