开发者

C pointer question, dereferencing crash

Why do this work?

开发者_开发技巧
    int *var;

while(scanf("%d", &var) && *var != 0)
        printf("%d \n", var);

While this does not?

    int *var;

while(scanf("%d", &var) && var != 0)
    printf("%d \n", var);

Doesn't * (dereference operator) give you the value pointed by the pointer? So why does *var != 0 crash the program, while var != 0 does not?


This worked:

int* var = malloc(sizeof(int));

while(scanf("%d", var) && *var != 0)
    printf("%d \n", *var);

Doing a refresher course on C, glad I did it.

I realized that scanf(&var) is for regular variables, while scanf(var) is for pointers. But completely forgot about the memory, thank you!


I'm not sure what you mean by "works," but the first one is wrong because you are taking what var points to and comparing it to zero in the first example, and since var has been initialized to what the user entered, what var points to is not likely to be a valid place.

*var != 0

This takes the value pointed to by the user-defined var.

Note that in the scanf, you are scanning an integer into int **, rather than int *, and printf is using %d to print a pointer, rather than an integer.

Things may seem to work or fail when you do undefined things for various reasons. You should understand why the code you're writing is correct, rather than putting down some code, and changing it until it works.


You pass an int* to sscanf, not int**. Either remove the * from the first declaration or initialize it to something like malloc(sizeof(int)) and remove the & from the sscanf call.


In both cases you are passing scanf() the adress of an int where the format string makes it expect an int itself.
So I'd say they both invoke undefined behavior. That the first one crashes while the second one doesn't is just one of many ways this can manifest. It could just as well be the other way around, or both crashing, or none, or none, except when you don't look, or at full moon. Undefined behavior does all that and much more.


(1) int i; // reserves an integer
(2) scanf("%d",&i); // writes to the address of i
(3) int *var; // is a pointer pointing to some unpredictable place 
(4) int *var = &i; // would point exactly to the adress of i
(5) scanf("%d",var) // would be the same as (2)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜