LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

free memory in function call

In my function call as the following:
 
void TryFreeMemory(char *str)
{
    char *str1;
    str1 = calloc(100, sizeof(char));
 
    str1 = "Hello";
    strcpy(str, str1);
    free(str1);
}
 
When it runs until free(str1) ---> an error occured (please see the attacment)???
 
*) If I have to use calloc to do something inside the function, before leaving the fuction ... how I can free it?
 
Thanks for any help
 
0 Kudos
Message 1 of 3
(3,182 Views)
Don't use assignment (=) to set the contents of a variable allocated by calloc.  Use strcpy().
 
You create a string constant with the following statement.
str1 = "Hello";
"Hello" is assigned memory at compile time.  When the above statement is executed, you change the value of the str1 pointer to point to wherever the string constant is in memory.  It no longer points to the memory allocated by calloc.  You can watch this in the debugger.  Set a breakpoint at str1 = "Hello";.  Point to str1 and see the value of the pointer.  Press F10 to continue to the next statement.  Check the value of the pointer again.  The pointer has changed, not just the contents.
 
Try this instead.
 
void TryFreeMemory(char *str)
{
    char *str1;
    str1 = calloc(100, sizeof(char));
 
    strcpy(str1, "Hello");
    strcpy(str, str1);
    free(str1);
}
 
0 Kudos
Message 2 of 3
(3,174 Views)
You solve my problem
Many thanks Smiley Happy
0 Kudos
Message 3 of 3
(3,151 Views)