C语言中的memset和malloc

465 阅读1分钟

[1]memset的使用

#include <string.h>

void *memset(void *s, int c, size_t n);

  • 功能:向s执行的地址中赋值c的内容,大小是n
  • 参数:
@s:要赋值的首地址
@c: 要赋值的内容
@n: 大小,单位是字节
  • 返回值:返回清空内存的首地址 eg: memset(cls,0,sizeof(*cls));
    ☞将cls指向的地址全部设置为0,大小是(sizeof(*cls));

[2]动态内存分配malloc

#include <stdlib.h>

void *malloc(size_t size);

  • 功能:动态分配内存(在堆区分配内存)
  • 参数:@size:分配内存的大小,单位是字节
  • 返回值:成功:分配到的内存的首地址,失败:返回NULL

void free(void *ptr)

  • 功能:释放堆上的内存
  • 参数:@ptr:首地址
  • 返回值:无

eg:

int *p = NULL;
    p = malloc(sizeof(int));
    if(p == NULL){
    printf("alloc memory error\n");
    return -1; 
    *p = 10; 
		
    printf("*p = %d\n",*p);
			
    if(p != NULL){  
    free(p);   //===>释放内存
    p = NULL;  //将指针和指向的内存断开链接
}   
}