Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an allocated variable

Tags:

People also ask

What is memory for a variable allocated?

When a variable is declared compiler automatically allocates memory for it. This is known as compile time memory allocation or static memory allocation. Memory can be allocated for data variables after the program begins execution. This mechanism is known as runtime memory allocation or dynamic memory allocation.

What happens when you free a pointer in C?

As soon as a pointer is passed to free() , the object it pointed to reaches the end of its lifetime. Any attempt to refer to the pointed-to object has undefined behavior (i.e., you're no longer allowed to dereference the pointer).

How memory allocated by malloc () or calloc () function can be deallocated?

C realloc() method “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.


I know we should free any variable allocated with malloc, but what if I return it in a function? Something like this:

char *somefunction(int somearg){
    char *str;

    str=(char *)malloc(sizeof(char *));

    //some code

    return str;
}

Should I free str? How could I do that?