c - 这里是否需要将指针设置为 NULL 并清空 char 数组?

标签 c arrays pointers

在下面的代码片段中,我使用 fgets()strtolstdin 获取两个输入。两个输入保存在不同的变量中。为了读取用户输入,我需要 fgets() 和 strtol() 的几个变量。以下是对 fgets()strtol() 的两次调用使用不同变量的详细解决方案:

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

int main(int argc, char *argv[]) {

    long int m_row;
    long int n_col;

    char rows_save[sizeof(long int)];
    char *ptr_rows_save;
    printf("Enter number of rows:\n");
    if (fgets(rows_save, sizeof(rows_save), stdin) != NULL)
    {
        m_row = strtol(rows_save, &ptr_rows_save, 10);

    }

    char cols_save[sizeof(long int)];
    char *ptr_cols_save;
    printf("Enter number of columns:\n");
    if (fgets(cols_save, sizeof(cols_save), stdin) != NULL)
    {
        n_col = strtol(cols_save, &ptr_cols_save, 10);

    }
    return EXIT_SUCCESS;
}

如您所见,对于程序从标准输入接收的每个数字,我使用一个新数组和一个指向数组的新指针。为了锻炼目的(或者为了好玩),我尝试避免这样做。为了实现此目的,我使用单个 char 数组和一个指向数组的指针,但保留对 fgets()strtol() 的两个单独调用:

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

int main(int argc, char *argv[]) {

    long int m_row;
    long int n_col;

    char save[sizeof(long int)];
    char *ptr_save;
    printf("Enter number of rows:\n");
    if (fgets(save, sizeof(save), stdin) != NULL)
    {
        m_row = strtol(save, &ptr_save, 10);
        ptr_save = NULL;
        save[0] = '\0';
    }

    printf("Enter number of columns:\n");
    if (fgets(save, sizeof(save), stdin) != NULL)
    {
        n_col = strtol(save, &ptr_save, 10);
        ptr_save = NULL;
        save[0] = '\0';
    }
    return EXIT_SUCCESS;
}

为了安全起见,我将指针*ptr_save设置为NULL,并通过将第一个元素设置为\0来清除字符数组code> 在我读入用户输入并使用 strtol() 处理它之后。但是,如果我没有将指针设置为 NULL 并清除字符数组,代码是否同样安全? (对于那些想知道的人,稍后将在代码中检查用户输入。)

最佳答案

您应该阅读 strtol() 的文档和 fgets() .

因为您实际上并未使用 endptr ( ptr_save ,我的意思是),没有必要将其设置为 NULL ...并且您(正确地)通过了 &ptr_savestrtol() ,所以strtol()不会关心你设置ptr_saveNULL 。事实上,在给出的示例中,您没有对 ptr_save 执行任何操作,你可以通过 NULL直接联系strtol()并且不使用变量...但是,您应该使用 ptr_save正确地检查它之后指向的内容以验证 strtol() 的结果。您还应该清除 errno在每个 strtol() 之前调用并随后检查 - 这是检测范围和基本错误的唯一方法。

fgets()不关心NULL s,领先或其他,在缓冲区中,如果在调用过程中出现问题,则不能保证您的领先 NULL仍然会在那里。您应该检查 fgets() 的结果看看它是成功还是失败,而不是赌博 NULL保留在缓冲区的开头。

此外,sizeof(long int)返回 long 占用的字节数...这不是表示以 10 为基数的 long 所需的最大字符数。

最后,在这个函数的范围内,ptr_save 成功 strtol() 后生效和save将在成功后正确地以空值终止 fgets() ...因此,只要您检查结果,在任何一种情况下写入 null 都不会获得安全性。

关于c - 这里是否需要将指针设置为 NULL 并清空 char 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30137112/

相关文章:

javascript - 使用单选按钮来计算测验的分数

c++ - 打印引用类的指针地址

c - 如何使用数组下标运算符将结构体中的成员地址传递给 `scanf` ?

c - Malloc/free 双重释放或损坏错误

c++ - 两个数组之间的共同功能?

c - C 中的 switch 函数可以处理所有情况

java - 如何调用 ArrayList 中数组的方法?

c - 如何在函数中使用 realloc() 并访问值?

c - 一个顶点的 Bellman-ford 算法

c++ - 内存对齐、结构和 malloc