Home > Blockchain >  Default value for a bool within a struct in C when accessed by dereferencing a pointer allocated mem
Default value for a bool within a struct in C when accessed by dereferencing a pointer allocated mem

Time:04-05

Consider the code below -

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

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

I know that calloc by default initializes memory to 0 (or equivalent). Would that still be the case for valid. Is it safe to say that:

ptr->valid;

would always return False (unless explicitly initialised to true) for dereferencing a pointer(like ptr) which was allocated memory using calloc.

CodePudding user response:

calloc() gives you a zero-initialized buffer. So, in ptr->valid will be zero, hence 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

The above snippet is from stdbool.h header file, in which it is clearly defined that false is 0.

And, will you stop using return 1;, it says error occurred instead use return 0; or return EXIT_SUCCESS;.

Try running the below code:

#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;
}

CodePudding user response:

(“C 2018” means the 2018 C standard.)

C 2018 6.2.5 6 says “… The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.”

C 2018 6.2.6.2 5 says “… For any integer type, the object representation where all the bits are zero shall be a representation of the value zero in that type.”

Therefore, any _Bool in space allocated with calloc will have the value zero until changed, and zero serves as false in various places in C.

(For completeness, C 2018 7.22.3.2 2 says memory allocated with calloc is initialized to all bits zero, and C 2018 6.2.5 17 says “The type char, the signed and unsigned integer types, and the enumerated types are collectively called integer types…”)

  • Related