使用 malloc 分配 0 字节

Using malloc to allocated 0 bytes

所以分配零字节是错误的,所以我想将 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;
}

否 - 根据 whats-the-point-in-malloc0,非空 return 值仍然可能对您的应用程序没有用。

If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.

参考:malloc

C standard(link是N1570稿)说:

If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

因此,如果您的 malloc_or_exit() 函数使用参数 0 调用,它可能会终止您的程序(如果 malloc(0) returns NULL ),或者它可能 return 一个不能被取消引用的非空指针(取消引用这样的指针会导致未定义的行为)。

如果您想将大小为零的分配视为错误,您可以修改包装函数(未测试):

void *malloc_or_exit(size_t size) {
    void *result;
    if (size == 0) {
        exit(EXIT_FAILURE);
    }
    else if ((result = malloc(size)) == NULL) {
        exit(EXIT_FAILURE);
    }
    else {
        return result;
    }
}
int i = 4;
void *x;
if( ( i != 0 ) && ( ( x = malloc(i) ) != NULL ) )
{
    // malloc successfull
}
else
{
    // not successfull
}
return 0;