简体   繁体   English

为什么这需要进行malloc?

[英]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. 没有提及动态分配的内存( malloc ),但它必须是指有效的内存。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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