当通过使用 calloc 取消引用分配内存的指针访问时,C 中结构中 bool 的默认值

Default value for a bool within a struct in C when accessed by dereferencing a pointer allocated memory using calloc

考虑下面的代码 -

typedef struct meh {
    int a;
    bool valid;
} var;

int main(){
    var *ptr = calloc(1, sizeof(var));
    return 1;
}

我知道默认情况下 calloc 将内存初始化为 0(或等效值)。有效的情况仍然如此吗?可以这样说吗:

ptr->valid;

对于使用 calloc 分配内存的指针(如 ptr)的取消引用总是 return False(除非明确初始化为 true)。

calloc() 给你一个 zero-initialized 缓冲区。因此,在 ptr->valid 中将为零,因此 false.

#define bool    _Bool
#if defined __STDC_VERSION__ && __STDC_VERSION__ > 201710L
#define true    ((_Bool)+1u)
#define false   ((_Bool)+0u)
#else
#define true    1
#define false   0
#endif

以上片段来自stdbool.h头文件,其中明确定义了false0.

而且,你会停止使用 return 1; 吗,它说 发生错误 而不是使用 return 0;return EXIT_SUCCESS;

试试运行下面的代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct meh {
    int a;
    bool valid;
} var;

int main(void)
{
    var *ptr = calloc(1, sizeof(var));
    if(ptr->valid)
        puts("true\n");
    else 
        puts("false\n");

    printf("%d\n", false); // prints 0
    free(ptr);
    return EXIT_SUCCESS;
}

(“C 2018”表示the 2018 C standard。)

C 2018 6.2.5 6 说“......类型_Bool和对应于标准有符号整数类型的无符号整数类型是标准无符号整数类型

C 2018 6.2.6.2 5 说“......对于任何整数类型,所有位都为零的对象表示应是该类型中值零的表示。”

因此,分配给 calloc 的 space 中的任何 _Bool 在更改之前将具有值零,并且零在 C 中的各个地方用作假。

(为了完整起见,C 2018 7.22.3.2 2 表示使用 calloc 分配的内存被初始化为所有位零,而 C 2018 6.2.5 17 表示“类型 char,已签名和无符号整数类型,枚举类型统称为整数类型……”)