[英]printf(“%d\n”, 1000000001) cause Segmentation fault?
我不知道为什么,gcc版本4.9.2(Ubuntu 4.9.2-10ubuntu13 x86_64)
Breakpoint 1, convertToTitle (n=1000000001) at excel_sheet_column_title.c:14
14 printf("%d\n", n);
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400697 in convertToTitle (n=1000000001) at excel_sheet_column_title.c:14
14 printf("%d\n", n);
(gdb) p n
$1 = 1000000001
该函数的完整代码,仅在主函数中调用了具有1000000001的函数:
char *convertToTitle(int n)
{
int mod, idx, last = n / 26 + 1;
char str[last], *title, *tp;
printf("%d\n", n);
idx = last;
while (n > 26) {
mod = n % 26;
if (mod > 0) {
str[--idx] = mod - 1 + 'A';
} else if (mod == 0) {
str[--idx] = 'Z';
n -= 1;
}
n /= 26;
}
if (n > 0) {
str[--idx] = n - 1 + 'A';
}
title = (char *)malloc((last - idx + 1) * sizeof(char));
tp = title;
for (; idx < last; idx++) {
*tp++ = str[idx];
}
*tp = '\0';
return title;
}
您的last
很大。 将其移到本地函数之外(或将其标记为静态),以避免出现段错误。
作为替代(也是正确的)解决方案,请计算last的正确值。
(我认为您想记录26 n +1)
26 最后 > = n
最后=对数26 n
last = ceil(log(n) / log(26)) + 1;
str[]
所需缓冲区大小的计算str[]
导致数组大小过大, last
为1000000001/26 + 1
。 该数组大小不支持编码为局部变量。
需要的是关于log26(n)
小得多的数组。
对于int n
各个值,几乎不需要“调整大小”缓冲区。 只需使用适用于INT_MAX
的恒定大小INT_MAX
。
由于int
的位大小约为log2(INT_MAX)+1
,
#include <limits.h>
#define ABOUT_LOG2_26 4.7
#define BUF26_SIZE ((int)(sizeof(int)*CHAR_BIT/ABOUT_LOG2_26 + 2))
char *convertToTitle(int n) {
char str[BUF26_SIZE];
...
// Also cope with negative values of n
if (n < 0) Handle_Error();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.