Memory allocated by malloc won’t be freed after the function returns, and it will be freed when the process exits. So we can use malloc to allocate memory which can be used during the whole life of the program.
But when we use malloc in functions we should avoid this case:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>
void test(char* a_) {
a_ = (char *)malloc(sizeof(char));
*a_ = 'x';
printf("*a_ = %c\n", *a_);
return;
}
int main() {
char* a = NULL;
test(a);
printf("*a = %c\n", *a);
return 0;
}
This program will cause segmentation fault because when entering test it will copy a to a_ and when test finishes a_ will be released. So in function main, a is still NULL. The reference to NULL causes the segmentation fault.
The right way to do this is as follows.
- Allocate in function and return the pointer.
1
2
3
4
char* test(){
char *a_ = (char *)malloc(sizeof(char));
return p;
}
- Use secondary pointer.
1
2
3
void test(char **a_){
*a_ = (char *)malloc(sizeof(char));
}