c - 这个指针返回安全吗?
问题描述
几天前,我想找到一个安全的替代方案,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指针被设置为在函数中本地定义的变量吗?
这是否意味着一旦转换完成并且局部变量超出范围,它可能会被覆盖并且我们不能再依赖该值?
我可能只是遗漏了一些东西,但是目前我不明白这是一种安全的解决方法。
解决方案
*out = l;
不设置out
,它设置*out
。即,无论它out
已经指向的是什么,因为它取消了指针的引用。只要传入一个有效的地址,该函数就会修改一个非本地对象。
推荐阅读
- ios - 如何将 UIImage 转换为 .JPEG 格式并将其发送到服务器?
- php - 有人能告诉我为什么这个简单的 PHP 循环不起作用吗?
- blob - 使用 JS 从 UUID 获取本地 BLOB
- java - 在字符串 "}," 之后添加新行
- git - 为什么 Jenkins 和 Github 不会触发拉取请求?
- node.js - 使用 NodeJs 从自动下载链接请求文件
- go - 树递归 - 如何避免“函数结束时缺少返回”?
- java - JAVA 示例中的嵌套 JSON 对象检索
- android - 在视图寻呼机布局中加载滑翔图像
- arrays - 在嵌套数组 MongoDB 中更新或插入新数据