I've some trouble understanding how to free my memory correctly in following codesnippet:
char *func(char* s){
/* do something with s */
// pass s to function, create new string, return this string
s = function_allocating_mem(s);
// pass s to function, create new string, return this string
s = other_function_allocation_mem(s);
/* do other stuff again */
return s;
}
int main(void){
char str[] = "somestring";
str = func(str);
}
Now I allocated different sizes of memory two times. But if I get it right, I just change the pointer address and never free the memory.
I don't really know, what to google to find an example
Is that correct and how would I change it?
EDIT: I removed the second parameter of the function. It was not necessary and confusing.
In code You've provided, correct way to free memory would be:
char *s2;
s2 = other_function_allocation_mem(s);
free( s );
s = s2;
...
free( s );
return ns;
When you allocate memory from the heap in your program, you have to have a clear understanding of:
Where memory from heap is allocated in your program.
How the ownership of heap allocated memory is transferred from one function to the next, and
Where it is deallocated before the program ends.
In your case, assuming function_allocating_mem
and other_function_allocation_mem
don't call free
on the input argument, you have to make sure that the memory allocated in those functions is deallocated in either fun
or main
.
char *func(char* s, const char* os){
char* s1 = NULL;
char* s2 = NULL;
/* do something with s and os */
// pass s to function, create new string, return this string
s1 = function_allocating_mem(s);
// pass s to function, create new string, return this string
s2 = other_function_allocation_mem(s1);
/* do other stuff again */
// Deallocate memory that was allocated by function_allocating_mem().
free(s1);
// Memmory allocated by other_function_allocation_mem is returned to the
// calling function.
return s2;
}
int main(void){
char str[] = "somestring";
// This is not legal anyway.
// str = func(str, "some other string");
char* s = fun(str);
// Use s ...
// Before returning from this function, deallocate memory
// that was allocated in the call to fun().
free(s);
}
So many problems.
1. You declared that
func
takes two parameters.
Then you only called it with one param.
2. You declared that
func
returns a
char*
, then you try to assign that to a
char[]
.
Arrays and pointers are related, but they are not interchangable.
3. In
func
, you never use param
os
.
4. You return variable ns
. It was never declared.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.