Home > Mobile >  Are dereferenced values of a global/local struct pointer always set to 0 (or equivalent) by default?
Are dereferenced values of a global/local struct pointer always set to 0 (or equivalent) by default?

Time:04-04

I know that global/static variables are by default set to 0 or equivalent in C.

How about a pointer to a struct?

For instance, consider the code below -

typedef struct meh
{
    int * ptr;
    int a;
    char c;
}var;

var *p;

int main(){
    p = malloc(sizeof(var));
    var *p1 = malloc(sizeof(var));

    printf("%d\t%p\t%c", p->a, p->ptr, p->c);
    printf("\n%d\t%p\t%c", p1->a, p1->ptr, p1->c);

    return 1;
}
//Output for both cases : 0 (nil) '\0'

Are dereferenced values for a struct pointer always set to 0 irrespective of the scope of the pointer? or is there a more specific rule at play here.

CodePudding user response:

Memory returned by the malloc function is uninitialized. Whether the returned pointer is assigned to a local variable or a global variable doesn't matter.

This means the pointed-to objects have indeterminate values, and reading them can cause undefined behavior.

If you used the calloc function to allocate memory, the returned memory has all bytes set to 0. This means that integer and floating point types will have the value 0. Pointer values will be NULL if a null pointer is represented as all bytes 0. On most systems you're likely to come across this will be the case, but it's not true in general.

CodePudding user response:

Those value aren't real zeroes they are the result of undefined behavior. Its just a coincidence that those values are 0. The pointer returned by malloc() is not fixed in terms of its value. Use calloc() to initialize them to 0. You have initialized your variable p and p1 by calling malloc(), but you haven't initialized the members of your struct hence they aren't initialized at the moment of printing them to stdout.

Scope your both variable are not responsible for those values

You can initialize them like:

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

typedef struct meh
{
    int * ptr;
    int a;
    char c;
}var;

var *p;

int main(void){
    p = malloc(sizeof(var));
    var *p1 = malloc(sizeof(var));

    p->ptr = malloc(2 * sizeof(int));
    p1->ptr = malloc(3 * sizeof(int));

    p->a = 100;
    p1->a = -100;

    p->c = 'T';
    p1->c = 'C';

    printf("%d\t%p\t%c", p->a, p->ptr, p->c);
    printf("\n%d\t%p\t%c", p1->a, p1->ptr, p1->c);

    free(p->ptr);
    free(p1->ptr);
    free(p);
    free(p1);

    return EXIT_SUCCESS;
}

Output:

100     0x8542e0    T
-100    0x854300    C
  • Related