sameer karjatkar
sameer karjatkar

Reputation: 2057

Memory Consumption?

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 .

Upvotes: 2

Views: 345

Answers (4)

Khoth
Khoth

Reputation: 13328

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.

Upvotes: 0

vasi
vasi

Reputation: 1036

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

Upvotes: 5

schnaader
schnaader

Reputation: 49719

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

Upvotes: 0

Daniel LeCheminant
Daniel LeCheminant

Reputation: 51081

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.

Upvotes: 8

Related Questions