因此,分配零字节是不明确的,所以我想把0字节视为失败。请问这代码做的伎俩使用malloc分配0字节
#include <stdio.h>
#incude "xmalloc.h"
void *malloc_or exit(size_t nbytes, const char *file, int line){
void *x; //declarea void pointer
if ((x = malloc(nbytes)) == NULL){
fprintf(stderr. " %s: line %d: malloc(%zu) bytes failed", file , line, nbytes);
exit(EXIT_FAILURE);
} else
return x;
}
实际上,对于'malloc'返回0不虐待定义;它明确定义为错误情况下的返回值。 – 2015-02-08 00:37:29
分配零字节可能会给你一个有效的指针(你可以传递给'free')或'NULL',它是实现定义的。见例如[这个'malloc'参考](http://en.cppreference.com/w/c/memory/malloc)。 – 2015-02-08 00:38:28
@JoachimPileborg'NULL'也是一个有效的指针,你可以传递给'free()';) – Quentin 2015-02-08 00:51:30