不明白为什么我会遇到分段错误
当我将一个数组传递到带有签名的动态库中的函数中时:
void itoa(int n, char s[]);
并从我的主函数中调用它:
int main(int argc, char *argv[])
{
if (argc > 1) {
char *arg = argv[1];
printf("%s\n", arg);
}
char str[15]={'0', '0', '0', '0', '0',
'0', '0', '0', '0', '0',
'0', '0', '0', '0', '\0'};
itoa(INT_MIN, str);
printf("%s\n", str);
return 1;
}
使用 gdb 遍历代码时,我可以看到程序在以下行崩溃:
s[i++] = n % 10 + '0';
请注意,声明了 i 的初始值0 位于函数顶部。
为什么会崩溃?
更新
请注意,它在本地运行。
#include <stdio.h>
#include <limits.h>
#include "c_lib.h"
void itoa_local(int n, char s[])
{
int min_int = 0;
int i, sign = 0;;
if (INT_MIN == n) {
min_int = 10;
n++;
}
if ((sign = n) < 0) n = -n;
do {
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0) s[i++] = '-';
s[i] = '\0';
if (min_int == 10) s[0]++;
reverse(s);
}
int main(int argc, char *argv[])
{
if (argc > 1) {
char *arg = argv[1];
printf("%s\n", arg);
}
char str[15]={'0', '0', '0', '0', '0',
'0', '0', '0', '0', '0',
'0', '0', '0', '0', '\0'};
itoa_local(INT_MIN, str);
printf("%s\n", str);
return 1;
}
When I pass an array into a function in a dynamic library with the signature:
void itoa(int n, char s[]);
and calling it from my main function:
int main(int argc, char *argv[])
{
if (argc > 1) {
char *arg = argv[1];
printf("%s\n", arg);
}
char str[15]={'0', '0', '0', '0', '0',
'0', '0', '0', '0', '0',
'0', '0', '0', '0', '\0'};
itoa(INT_MIN, str);
printf("%s\n", str);
return 1;
}
Walking through the code with gdb I can see that the program is crashing on the following line:
s[i++] = n % 10 + '0';
Note that i's initial value is declared 0 at the top of the function.
Why is it crashing?
UPDATE
Note that it works locally.
#include <stdio.h>
#include <limits.h>
#include "c_lib.h"
void itoa_local(int n, char s[])
{
int min_int = 0;
int i, sign = 0;;
if (INT_MIN == n) {
min_int = 10;
n++;
}
if ((sign = n) < 0) n = -n;
do {
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0) s[i++] = '-';
s[i] = '\0';
if (min_int == 10) s[0]++;
reverse(s);
}
int main(int argc, char *argv[])
{
if (argc > 1) {
char *arg = argv[1];
printf("%s\n", arg);
}
char str[15]={'0', '0', '0', '0', '0',
'0', '0', '0', '0', '0',
'0', '0', '0', '0', '\0'};
itoa_local(INT_MIN, str);
printf("%s\n", str);
return 1;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案在最初的帖子中。我回答了我自己的问题,所以我不必删除它。主要是档案原因。
The answer is in the initial post. I answered my own question so I did not have to delete it. Archival reasons mainly.