简体   繁体   English

在scanf()读取结果导致进程终止后,C ++删除指针

[英]C++ delete pointer after scanf() reading results in process termination

Could you explain to me why on earth this code terminates the process? 您能否向我解释为什么该代码会终止该过程?

#include<cstdio>

int main(){
    int *wsk = new int[2];

    scanf("%d %d", wsk[0], wsk[1]); // relevant line

    delete [] wsk;
    wsk = new int[10];
    return 0;
}

Whereas this one does not: 而这一点没有:

#include<cstdio>

int main(){
    int *wsk = new int[2];

    scanf("%d %d", &wsk[0], &wsk[1]); // relevant line, mark the two '&'

    delete [] wsk;
    wsk = new int[10];
    return 0;
}

scanf takes pointers. scanf需要指针。

It has to know the address of where to put the read in value. 它必须知道将读取值放在何处的地址

wsk[0] and wsk[1] are some random (actually, undefined) int s. wsk[0]wsk[1]是一些随机的(实际上是未定义的) int s。 They are used as addresses, but they were invalid addresses. 它们用作地址,但它们是无效的地址。 Seg fault. 段故障。

&wsk[0] and &wsk[1] , or more concisely, wsk and wsk+1 , are a valid addresses, where scanf can write an int . &wsk[0]&wsk[1]或更wskwsk+1是有效的地址, scanf可以在其中写入int

Because you are not passing in pointers to the scanf function in the first case. 因为在第一种情况下,您没有传递指向scanf函数的指针。 You are passing in the value of wsk[0] and wsk[1] and treating those values as pointers. 要传递在WSK [0]和WSK [1]的和治疗这些值作为指针。

a) Both codes will terminate at least when they are finished. a)这两个代码至少将在完成时终止。
b) You´re not deleting all reservations before the program ends. b)您不会在程序结束之前删除所有保留。
c) You program is a mix of C and C++. c)您的程序是C和C ++的混合体。
... ...
d) scanf take addresses to variables. d)scanf将地址分配给变量。 &

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

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