Reading data into an uninitialized char pointer variable using fgets crashes at the second read

左心房为你撑大大i 提交于 2021-02-05 08:55:07

问题


I am aware that we cannot read data into an uninitialized char pointer using fgets. There are quite a few questions relating to this very point here on stackoverflow. All the answers point to the fact that you can't load data into an uninitialized pointer variable.

The program shown in the first code snippet is able to populate the first uninitialized char pointer (*str2) using fgets but, crashes while trying to read data into the second uninitialized char pointer (*str3).

I can get it to work using the traditional methods like allocating memory to the pointer up-front (as shown in the second code snippet below) before populating. My question is why does it work for the first variable but not for the second?

The Problem Code

#include <stdio.h>

int main()
{
    char str1[100], *str2, *str3;
    // Prints fine

    printf("First String: ");
    fgets(str1, 20, stdin);
    printf("%s", str1);

    // Prints fine      
    printf("Second String: ");
    fgets(str2, 20, stdin);
    printf("%s", str2);

    // Program crashes on this input
    printf("Third String: ");
    fgets(str3, 20, stdin);
    printf("%s", str3);

    return 0;

}

The Working Code

#include <stdio.h>

int main()
{
    char str1[100], str2[20], str3[20];
    printf("First String: ");
    fgets(str1, 20, stdin);
    printf("%s", str1);

    printf("Second String: ");
    fgets(str2, 20, stdin);
    printf("%s", str2);

    printf("Third String: ");
    fgets(str3, 20, stdin);
    printf("%s", str3);

    return 0;

}

回答1:


In your case

// Prints fine      
printf("Second String: ");
fgets(str2, 20, stdin);
printf("%s", str2);

contains the write to uninitialized pointer, which contains indeterminate value, which means, it invokes undefined behavior.

Once your program has UB, nothing is guaranteed. One of the side-effects of having UB is to appear as "working (ab)normally", and a "crash" or segmentation fault is not guaranteed, either. It's just that, undefined.

Moral of the story: Do not try to reason with the output obtained from a program containing undefined behavior.




回答2:


Just because you are using an uninitialized pointer is not a guarantee that the program will crash. Undefined behavior often times results in unpredictability. In your particular case, on your machine and with your compiler the pointer just happens to point to valid memory even if uninitialized, but this may change from compiler to compiler and from machine to machine.



来源:https://stackoverflow.com/questions/55923967/reading-data-into-an-uninitialized-char-pointer-variable-using-fgets-crashes-at

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!