Details of using malloc (although the things are small, the impact of the problem is quite large, pay attention to it)

malloc uses the basic process:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE   sizeof(char) *100

int main()
{
        char *ptr =(char *)malloc(MAX_SIZE); /*申请堆内存*/
        if(ptr == NULL)              /*判断是否申请成功*/
        {
                printf("内存分配失败");
                exit(1);
        }

        memset(ptr, 0, MAX_SIZE);  /*清空申请内存*/

        strcpy(ptr,"可以使用了!!");	/*内存使用*/
        printf("mem is %s\n", ptr);

        free(ptr);             /*释放内存*/
        ptr = NULL;        /*指针赋空*/
        return 0;
}

Note: Use six steps to follow

1. Allocate memory space.

2. Check whether the memory allocation is successful. The first address of the memory is returned successfully, and NULL is returned on failure.

3. Clear the allocated memory space.

4. Use memory.

5. The memory needs to be released after use.

6. Leave the pointer empty. If you do not leave it empty after release, it will become a wild pointer in case you continue to use it later.

Published 20 original articles · Likes6 · Visits 10,000+

Guess you like

Origin blog.csdn.net/weixin_36662608/article/details/54580029