C 这个指针安全返回吗?
几天前,我想找到一个安全的替代C 这个指针安全返回吗?,c,pointers,scope,atoi,C,Pointers,Scope,Atoi,几天前,我想找到一个安全的替代atoi的方法,并找到以下代码作为对问题的回答: #include <assert.h> #include <ctype.h> #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> typedef enum { STR2INT_SUCCESS, STR2INT_OVERFLOW
atoi
的方法,并找到以下代码作为对问题的回答:
#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
已经指向的是什么,因为它取消了指针的引用。只要传入有效地址,函数就会修改非本地对象。参数是指向main
中变量i
的指针。稍后执行此操作时:
*out = l;
这不会更改out
,而是取消引用它并更改它指向的变量,即main
中的i
。因此,当函数返回时,i
将被修改
如果out
指向str2int
中的局部变量,则会出现指针指向无效内存的问题