1

I have a doubt related to freeing up the memory in C program. I don't know how memory gets freed up. below are two scenarios where I am not sure whether I do need to free up memory or not.

below is code snippet

int status=0;
char *grade="high";
status=getPreviousReports(grade, year);
free(grade);

my doubt is that getPreviousReports is doing a soap call and passing grade to it. After that it destroys the soap object in memory, that uses grade in forming soap object.

if I use below code then do I need not to free up grade explicitly ?

status= getPreviousReports("high", year);

Please help me in understanding how and when it is required to free up memory.

Thanks in advance.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
summary
  • 125
  • 1
  • 14
  • You only need to free what you allocate. The grade variable is just a pointer to a constant string. The grade variable is probably allocated in the stack for most implementations. It will "free" when you return from the function. The "high" constant is allocated permanently in some constant block of memory and cannot be freed. – lit Apr 02 '16 at 22:56

5 Answers5

4

Memory allocation in C is used by malloc, if memory is not being used (malloc) then there is nothing need to be free.

Paul
  • 41
  • 3
3

If you (or someone else) allocated the memory using malloc and family, then you free it, otherwise not. Function which returns memory allocated by malloc should normally document that for the caller to know.

In your particular case

char *grade="high"

there is no dynamic memory allocation involved, so no need to free.

my doubt is that getPreviousReports is doing a soap call and passing grade to it . After that it destroys the soap object in memory , that uses grade in forming soap object.

You need more information on what that function is doing internally, and whether it frees some of its parameters manually, e.g grade, which would be weird.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
2

"Hello" is a String literal. So, it will be there in the memory even if your GRADE variable goes out of scope or you change it to point to somewhere else or it was present even before you declared your GRADE variable.

And free function is used with memory blocks that you have requested during runtime using malloc(), i.e, dynamic memory allocation.

You haven't requested to allocate space for your "Hello" string during runtime and that's why you shouldn't be calling free on it.

abhiarora
  • 9,743
  • 5
  • 32
  • 57
1

As others have noted, in C, if [c][m][re]alloc() have not been used to create memory, then free() is typically not necessary. (see also strdup that also requires using free() )

In a more general sense, all memory in C is said to reside on either the heap or the stack. All of the memory you have created is clearly created on the stack, and does not need to be explicitly freed. Memory created this way is freed as it goes out of scope, or when the executable exits.

Examples of memory created on the heap (then freed) and stack (not freed) include:

int main() 
{
    int status=0;//created on the stack
    char *grade="high";//created on the stack


    char *buf = {0};//created here, but no memory yet
    char *temp = {0};//ditto
    char *dup = {0};//ditto
    //....
    buf = malloc(10);//on heap if successful.  free() now required at some point 
    if(buf)
    {
        strcpy(buf, "started..");
        temp = realloc(buf, 20);//on heap if successful
        if(!temp)
        {
            free(buf);
            return -1;
        }
        buf = temp;//new memory transferred to buf, free() now required at some point
        strcat(buf, "here");
        dup = strdup(buf);//on heap if successful, free() now required at some point
        if(!dup)
        {
           free(buf);//memory alloc failed, handle error and leave
           return -1;
        }
        //use buf and dup...
        free(buf);
        free(dup);
        //Note: temp is freed when buf is freed in this example
    }
    return 0;
}
Community
  • 1
  • 1
ryyker
  • 22,849
  • 3
  • 43
  • 87
0

Since you don't allocate (malloc, calloc) any memory you don't need to freeing it. I don't know what exactly getPreviousReports() is doing. But usually if some function allocates memory it takes care about freeing (but not the passed variables).

Additionally I would recommend you to use debugger and examine *grade after getPreviousReports() call.

Hope it helps...

Darko Djuric
  • 754
  • 4
  • 10
  • Thanks , for clarifying doubt . Based on these inputs i can optimised my code unto certain extent by declaring frequently used variables early as const char * instead of declaring inside methods. Thanks again . – summary Apr 03 '16 at 18:48
  • what is the scope of a variable in c ? The thing is my program runs 24 hours and restarts with reboot once in a day . I m calling method X () that calls getPreviousReports() , and X() gets called repetitively every 5 mins . Since i m declaring char * grade='high" inside x() instead of declaring it once in program . Would it get cleared off memory once x() returns out ? – summary Apr 03 '16 at 19:06
  • ouch, this is not a simple answer. It depends where is the declaration made. It could be between {}, or function scope, or file scope, or program scope (global variable). Please take look on following article [Scope and Storage Classes in C](http://aelinik.free.fr/c/ch14.htm) And yes, if you declare it in function it will not be available out of that function. – Darko Djuric Apr 03 '16 at 19:12
  • well. i am posting here actual code . ( removing code in between ) int call_GTW_Pending_Jobs(int argc , char * argv[],ClientConfig *ccfg, char * comkey) { SoapCtx *ctx, *ctx2; char *method="getPendingJobs"; err = soap_ctx_new_with_method(GTWurn, method, &ctx); if (err != H_OK) { log_error4(..); return 1; } // do something err = soap_client_invoke(ctx, &ctx2, GTWurl1, "CKZInc"); if (err != H_OK) { log_error4("[....]"); soap_ctx_free(ctx); return 1; } soap_ctx_free(ctx2); soap_ctx_free(ctx); soap_client_destroy(); return 0; } – summary Apr 03 '16 at 19:42
  • sorry for poor formatting .. do i need to declare char *method outside as const char * ..because call_GTW_Pending_Jobs is called repetitively after every 5 mins. or it will get freed once call_GTW_Pending_Jobs returns ? will that memory of method pointer will get released ? – summary Apr 03 '16 at 19:44
  • in the code above ```char *method``` will be recreated on each call of ```call_GTW_Pending_Jobs(int argc , char * argv[],ClientConfig *ccfg, char * comkey)``` function so this is perfectly fine. If you need a different values for method you could declare it out of function (as const char*) and pass it as argument. It depends of what exactly you want to achieve, but in both cases no worries about freeing. – Darko Djuric Apr 03 '16 at 19:53
  • Well, char * method will be recreated , but what will happen to previously created memory ? will that be released ? isn't that wise to declare it outside in header file as const char * and reuse it again ? The issue i am facing is the size of binary is increasing ? And it never happened before !! same program is running fine on other system without growing in size . So i m revising code .... – summary Apr 03 '16 at 19:58
  • The link provided is not opening and redirecting to some blocker page . – summary Apr 03 '16 at 20:01
  • "Well, char * method will be recreated , but what will happen to previously created memory? will that be released?" You don't create any new memory in this case, but only a pointer to your "getPendingJobs" string literal. In case of declaration inside of function you are creating new pointer to existing memory (old pointer is gone on exit from function). So basically the "reuse" that you want is already there. Memory leak that you have probably has nothing with this. – Darko Djuric Apr 03 '16 at 20:03
  • Thanks much Okrad . Really appreciate your help. I wasn't aware about literal concept in C. I thought every time new memory gets created on heap. Thanks – summary Apr 03 '16 at 20:13