Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C variable be deleted or removed at any time during the running of a program?

Tags:

c

free

I am wondering if it is possible to delete, that is remove from use, a C variable, say, for example, once the variable is used once?

I was reflecting some time ago on this subject, and one question arose in my mind.

C has many data types and we can create a variable of data type, say integer by the simple code

int i;

Once we have created a variable in this manner, how do we 'delete' it if we do not require it in future use?

I searched on the net, but did not find any C command that does this. By 'k is deleted', I mean 'k has ceased to exist'. I mean, once we do not need the variable, it is a waste, and should be removed.

C does provide the free() function, but it only works on memory allocated using calloc(), malloc(), or realloc().

So how does one remove, say, an int variable, once it has been used?

like image 357
Nihal Avatar asked Jun 09 '12 12:06

Nihal


People also ask

Can you delete a variable in C?

Use a tight scope around the variables (that's a pair of braces enclosing a sequence of statements). The variables are destroyed when the scope they're defined in is exited (and aren't created until the scope is entered). Otherwise, the answer's "No". Global variables can't be destroyed at all.

Can we delete a variable?

The Remove-Variable cmdlet deletes a variable and its value from the scope in which it is defined, such as the current session. You cannot use this cmdlet to delete variables that are set as constants or those that are owned by the system.

Which function is used to delete a variable?

The unset() function unsets a variable.

What happens to the local variables when the function is completed?

When the execution of the function terminates (returns), the local variables are destroyed. Codelens helps you visualize this because the local variables disappear after the function returns.


2 Answers

You don't. The object's lifetime ends once it goes out of scope (it is known as an automatic object, because it is automatically cleaned up).

e.g.

void foo() {
    int j = 3;

    while (blah) {
        int i = 5;
    }

    // i no longer exists
}

// j no longer exists
like image 89
Oliver Charlesworth Avatar answered Sep 20 '22 15:09

Oliver Charlesworth


In C, there's the concept of storage duration of an object, which determines its lifetime:

  • static storage lives for the entire execution of the program
  • thread storage lives till thread termination
  • automatic storage lives till the surrounding block is left
  • allocated storage needs explicit de-allocation via free()

Allocated storage aside, the language runtime will take care of reclaiming memory (eg decreasing the stack pointer to discard call frames, which 'frees' automatic storage).

like image 35
Christoph Avatar answered Sep 20 '22 15:09

Christoph