简体   繁体   中英

Why does this need to be malloc'd?

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

int main(){
    int * p = malloc(sizeof(int));
    *p = 10;
    *p += 10;
    printf("%d", *p);
}

It gives me the correct value if it is malloc'd but a bus error if I just declare it as:

int main(){
        int * p;
        *p = 10;
        *p += 10;
        printf("%d", *p);
    }

An uninitialized pointer is just that; uninitialized. Where do you expect it to point? It's value is indeterminate and reading/writing it results in undefined behavior.

It doesn't have to refer to dynamically allocated memory ( malloc ), but it does have to refer to valid memory. For example, this would be fine:

int main(void)
{
    int x;
    int *p = &x;
    *p = 10;
    *p += 10;
    printf("%d", *p);
}
#include<stdio.h>
#include<stdlib.h>
int main()
{

 int *ptr; 
 //*ptr=123;   Error here....Becuase it is like trying to store 
             //some thing into a variable without creating it first.

 ptr=malloc(sizeof(int)); // what malloc does is create a integer variable for you
                          // at runtime and returns its address to ptr,
                          // Which is same as if you assingned &some_variable 
                          // to ptr if it had been already present in your program.

 return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM