首页 > 解决方案 > 这个指针返回安全吗?

问题描述

几天前,我想找到一个安全的替代方案,atoi并找到以下代码作为对这个SO 问题的回应:

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

typedef enum {
    STR2INT_SUCCESS,
    STR2INT_OVERFLOW,
    STR2INT_UNDERFLOW,
    STR2INT_INCONVERTIBLE
} str2int_errno;

str2int_errno str2int(int *out, char *s, int base) {
    char *end;
    if (s[0] == '\0' || isspace(s[0]))
        return STR2INT_INCONVERTIBLE;
    errno = 0;
    long l = strtol(s, &end, base);
    /* Both checks are needed because INT_MAX == LONG_MAX is possible. */
    if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
        return STR2INT_OVERFLOW;
    if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
        return STR2INT_UNDERFLOW;
    if (*end != '\0')
        return STR2INT_INCONVERTIBLE;
    *out = l;
    return STR2INT_SUCCESS;
}


int main(void) {
  int i;
    /* Lazy to calculate this size properly. */
    char s[256];

    /* Simple case. */
    assert(str2int(&i, "11", 10) == STR2INT_SUCCESS);
    assert(i == 11);
    printf("%i", i);

    /* Negative number . */
    assert(str2int(&i, "-11", 10) == STR2INT_SUCCESS);
    assert(i == -11);
}

原始代码源


这不是不安全的,因为out指针被设置为在函数中本地定义的变量吗?
这是否意味着一旦转换完成并且局部变量超出范围,它可能会被覆盖并且我们不能再依赖该值?

我可能只是遗漏了一些东西,但是目前我不明白这是一种安全的解决方法。

标签: cpointersscopeatoi

解决方案


*out = l;不设置out,它设置*out。即,无论它out已经指向的是什么,因为它取消了指针的引用。只要传入一个有效的地址,该函数就会修改一个非本地对象。


推荐阅读