我一直在尝试以这种方式生成字符串:
一
B'/ P>
ž
AA
AB
ZZ
ZZZZ
我想知道为什么当达到'yz'时会出现Segmentation fault(core dumped)错误。我知道我的代码没有覆盖所有可能的字符串,如'zb'或'zc',但这不是重点,我想知道为什么会出现这个错误。我不是你编码的大师,所以请尽量解释清楚。谢谢:))
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
void move_positions (char s[]);
int main (int argc, char *argv[])
{
char s[28];
s[0] = ' ';
s[1] = '\0';
int a = 0;
for(int r = 'a'; r <= 'z'; r++)
{
for(int t ='a';t <='z'; t++)
{
for(int u = 'a';u <= 'z'; u++)
{
for(int y = 'a'; y <= 'z'; y++)
{
s[a] = (char)y;
printf ("%s\n", s);
if (s[0] == 'z')
{
move_positions(s);
a++;
}
}
s[a-1] = (char)u;
}
s[a-2] = (char)t;
}
s[a-3] = (char)r;
}
return 0;
}
void move_positions (char s[])
{
char z[28];
z[0] = ' ';
z[1] = '\0';
strcpy(s, strcat(z, s));
}
答案 0 :(得分:1)
首先,让我们在打开调试的情况下进行编译:
gcc -g prog.c -o prog
现在让我们在调试器下运行它:
> gdb prog
GNU gdb 6.3.50-20050815 (Apple version gdb-1822) (Sun Aug 5 03:00:42 UTC 2012)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin"...Reading symbols for shared libraries .. done
(gdb) run
Starting program: /Users/andrew/Documents/programming/sx/13422880/prog
Reading symbols for shared libraries +............................. done
a
b
c
d
e
...
yu
yv
yw
yx
yy
yz
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x00007fffc0bff6c5
0x0000000100000c83 in main (argc=1, argv=0x7fff5fbff728) at prog.c:22
22 s[a] = (char)y;
好的,它在第22行崩溃,试图s[a] = (char)y
。什么是a
?
(gdb) p a
$1 = 1627389953
所以你要设置数组s
的~160亿条。什么是s
?
(gdb) ptype s
type = char [28]
在28个元素阵列中保存160万个条目?那不行。看起来您需要在某些循环开始时将a
重置为零。