为什么这需要malloc&d; d?

时间:2014-04-07 22:48:09

标签: c pointers malloc

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

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

如果它是malloc,那么它给出了正确的值,但如果我将其声明为:

则会出现总线错误
int main(){
        int * p;
        *p = 10;
        *p += 10;
        printf("%d", *p);
    }

2 个答案:

答案 0 :(得分:4)

一个未初始化的指针就是这样;初始化。您认为它指向哪里?它的价值是不确定的,读/写它会导致不确定的行为。

不必引用动态分配的内存(malloc),但它必须引用有效的内存。例如,这没关系:

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

答案 1 :(得分:0)

#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;
}
相关问题