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 .
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 .
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).
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.
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
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.