user3897320
user3897320

Reputation: 87

C automatic variables

What happens if we free an automatic variable using free()?

What about in the following code: if n is static does it get automatically free'd after the last loop iteration, can we free it, or what?

for(count = 0; count < 5; count++) {  
    static int i += 1
}

Upvotes: 0

Views: 139

Answers (4)

Clifford
Clifford

Reputation: 93556

The single argument to free() is a pointer, passing a non-pointer will not compile, so the question is moot.

The effect of passing a pointer that was not previously returned from a heap allocation function and not previously passed to free() is undefined - but never useful, or correct, and usually fatal.

In practice, free() will assume the pointer is a block allocated from the heap; the implementation may detect the error, or it may corrupt the heap. The error may not be detected and will cause a failure undefined in nature at some later heap operation, making it very difficult to determine the original cause.

In a typical implementation allocated blocks are preceded by heap metadata; free() accesses this data by subtracting the size of the metadata from the pointer passed to it. For a non-heap allocated pointer, the data read will be invalid nonsense. The implementation may be able to validate this data and cause a runtime error, but in a simple implementation, the metadata may contain just the size of the block, and a block of undefined size and inappropriate location may be added to the heap.

Upvotes: 0

John Bode
John Bode

Reputation: 123578

The only valid arguments to free are the result of a previous call to one of the *alloc functions (malloc, calloc, or realloc) or NULL. That's it.

auto variables exist for the lifetime of their enclosing scope; attempting to call free on one will invoke undefined behavior (which may result in an access violation or a segfault).

static variables exist for the lifetime of the program, even if their visibliity is limited to a particular scope; the i in your for loop is allocated at program startup and held until the program terminates, but can only be accessed within the scope of the for loop. As with auto variables, attempting to call free on a static variable will invoked undefined behavior, and will probably result in a runtime error.

Upvotes: 0

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6049

If you free() an automatic variable the result is undefined.

static variables are cleaned up by the runtime. There is no need to free them.

free is only used on a pointer that you allocated with malloc/calloc

Upvotes: 0

haccks
haccks

Reputation: 106102

What happens if we free an automatic variable using free()?

It will invoke undefined behavior.

Argument to free must be a pointer that was returned by memory allocation function (malloc, calloc, realloc). The argument may also be a null pointer, in which case the call of free has no effect.

Upvotes: 3

Related Questions