3

我一直在尝试以这种方式生成字符串:

一个

b

.

.

z

抗体

.

.

Z Z

.

.

.

.

zzzz

我想知道为什么当它到达'yz'时会提示分段错误(核心转储)错误。我知道我的代码没有涵盖所有可能的字符串,例如“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));
}
4

1 回答 1

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

因此,您正在设置数组的第 160 万个条目s。是什么s

(gdb) ptype s
type = char [28]

在 28 元素数组中保存 160 万个条目?那是行不通的。看起来您需要a在某些循环开始时重置为零。

于 2012-11-16T19:43:05.390 回答