gpt4 book ai didi

c - 这个指针返回安全吗?

转载 作者:行者123 更新时间:2023-11-30 19:26:50 26 4
gpt4 key购买 nike

几天前,我想找到 atoi 的安全替代方案,并发现以下代码作为对 this 的响应所以问题:

#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);
}

Original code source

<小时/>

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

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

最佳答案

out参数是一个指针,指向main中的变量i。当您稍后执行此操作时:

*out = l;

这不会更改out,而是取消引用它并更改它指向的变量,即main中的i >。因此,当函数返回时,i 被修改。

如果out指向str2int中的局部变量,那么就会遇到指针指向无效内存的问题。

关于c - 这个指针返回安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56561942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com