Home > Back-end >  C language to declare a pointer variable, the system will automatically allocate memory? If it'
C language to declare a pointer variable, the system will automatically allocate memory? If it'

Time:07-20

I am a freshman who has only learned C language

Statement of int variables at the same time, there was a piece of memory in the computer, if there is no initialization, stored in the memory is rubbish, but still have the memory, my understanding is that statement pointer variable, should also opened up a piece of memory, but if no initialization, stored in the memory is not well-known address (spam), like int variable declaration.

CodePudding user response:

int a; is an uninitialized int variable. The compiled code will reserve a piece of memory for that variable. It's content is not specified. It can contain anything when reading it. Reading it is Undefined Behaviour.

int* b; is also an unitialized variable, but of type int*. the compiled code will also reserve a piece of memory to hold that variable. Since it is a pointer, it has the ability to be dereferenced. However, this pointer is not initialized to a valid address of an int. The same rules apply to pointers here. Reading it before it is initialized invokes Undefined Behaviour.

CodePudding user response:

#include<stdio.h>

int main(void) {
    int *p1 = NULL;
    int *p2;

    if (p1 != NULL) {
        printf("p1 is not NULL \n");
    } else {
        printf("p1 is null \n");
    }

    if (p2 != NULL) {
        printf("p2 is not NULL \n");
    } else {
        printf("p2 is null \n");
    }

    return 1;
}

output:

p1 is null 
p2 is not NULL

Please check the code; If you just delcare a pointer like "*p2" without assign, p2 is initialized.

  •  Tags:  
  • c
  • Related