Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable reuse in C

Tags:

c

The code I'm looking at is this:

for (i = 0; i < linesToFree; ++i ){
    printf("Parsing line[%d]\n", i);

    memset( &line, 0x00, 65 );
    strcpy( line, lines[i] );

    //get Number of words:
    int numWords = 0;

    tok = strtok(line , " \t");
    while (tok != NULL) {
        ++numWords;
        printf("Number of words is:  %d\n", numWords);
        println(tok);

        tok = strtok(NULL, " \t");
    }
}

My question centers around the use of numWords. Does the runtime system reuse this variable or does it allocate a new int every time it runs through the for loop? If you're wondering why I'm asking this, I'm a Java programmer by trade who wants to get into HPC and am therefore trying to learn C. Typically I know you want to avoid code like this, so this question is really exploratory.

I'm aware the answer is probably reliant upon the compiler... I'm looking for a deeper explanation than that. Assume the compiler of your choice.

like image 960
avgvstvs Avatar asked Oct 08 '11 20:10

avgvstvs


2 Answers

Your conception about how this works in Java might be misinformed - Java doesn't "allocate" a new int every time through a loop like that either. Primitive type variables like int aren't allocated on the Java heap, and the compiler will reuse the same local storage for each loop iteration.

On the other hand, if you call new anything in Java every time through a loop, then yes, a new object will be allocated every time. However, you're not doing that in this case. C also won't allocate anything from the heap unless you call malloc or similar (or in C++, new).

like image 145
Greg Hewgill Avatar answered Oct 05 '22 06:10

Greg Hewgill


Please note the difference between automatic and dynamic memory allocation. In Java only the latter exists.

This is automatic allocation:

int numWords = 0;

This is dynamic allocation:

int *pNumWords = malloc(sizeof(int));
*pNumWords = 0;

The dynamic allocation in C only happens explicitly (when you call malloc or its derivatives).

In your code, only the value is set to your variable, no new one is allocated.

like image 24
Constantinius Avatar answered Oct 05 '22 07:10

Constantinius