概述
最近,看了有关malloc(0)的返回值以及其他一些问题的讨论,我把自己的感受和看法记录如下:
问题:
char* ptr = malloc(0*sizeof(char));
if(NULL == ptr) {
printf("got a NULL pointer");
} else {
printf("got a Valid pointer");
}
通过查看malloc的man手册:The malloc() function allocates size bytes and returns a pointer to the allo‐cated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().这句话翻译起来,就是传个0的话,返回值要么是NULL,要么是一个可以被free调用的唯一的指针。
通过下面代码来测试:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
int alloc_memory(char *p , int size)
{
printf("nbefore malloc %pn",p);
p = (char *)malloc(size);
if (!p) {
printf("malloc errorn");
return -1;
}
printf("len of malloc(%d) is %lu,the ture is %lun", size, strlen(p), malloc_usable_size(p));
printf("the first member of malloc(%d) is %p : %d n", size, p, *p);
*p = 10;
printf("set the first member of malloc(%d) is %p : %d n", size, p, *p);
memset(p, '