为什么这些指针会导致崩溃? [英] Why do these pointers cause a crash?

查看:158
本文介绍了为什么这些指针会导致崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对为什么以下代码崩溃感到困惑:

I'm a bit confused as to why the following code crashes:

int main(){
    int *a;
    int *b;

    *a = -2;
    *b = 5;  //This line causes a crash on my system.

    return 0;
}

由于声明,是否应该在运行前自动为两个指针和两个整数分配内存?

Shouldn't memory automatically be allocated for two pointers and two integers before run-time because of the declarations?

还是必须始终明确分配内存?

Or must you always explicitly allocate memory?

推荐答案

否.您只声明了指针,没有声明它们所指向的指针.指针是在堆栈上分配的,并且由于您还没有将它们初始化为任何东西,因此它们的值是垃圾.

No. You've only declared the pointers, not what they point to. The pointers are allocated on the stack, and since you've not initialized them to anything, their values are garbage.

int main() {
    int a = 7;
    int *p_a;    // p_a contains whatever garbage was on the stack at its
                 // location when main() is called. (Effectively points nowhere).

    p_a = &a;    // p_a points to (gets the address of) variable a, also on
                 // the stack.

    printf("Before: a = %d\n", a);   // prints 7

    *p_a = -2;      

    printf("After: a = %d\n", a);    // prints -2

    return 0;
}

我将编写上面的示例,并在调试器中逐步进行.您会明白我对p_a所指的含义.

I would code up the above example, and step through it in a debugger. You'll see what I mean about what p_a is pointing to.

由于声明,是否应该在运行前自动为两个指针和两个整数分配内存?

Shouldn't memory automatically be allocated for two pointers and two integers before run-time because of the declarations?

我只看到您指定了两个指针.这两个整数在哪里?

I only see you specifying two pointers. Where are the two integers?

还是必须始终明确分配内存?

Or must you always explicitly allocate memory?

指针必须指向某物.要么是堆栈上的局部变量,要么是堆中malloc的内存.

Pointers have to point to something. Either local variables on the stack, or malloc'd memory from the heap.

这篇关于为什么这些指针会导致崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆