【发布时间】:2014-04-15 03:33:50
【问题描述】:
这里是菜鸟。弹出打开我的虚拟机以编辑程序,但是(据我所知),在我进行任何更改之前,我遇到了以前没有发生的分段错误。我尝试评论可能的原因,但无济于事。
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main (int argc, string argv[])
{
int keyOk = 0;
string keyword = argv[1];
int keyLength = strlen(keyword);
do
{
if (argc != 2)
{
printf("TOo many words\n");
return 1;
}
else
{
for (int i = 0; i < keyLength; i++)
{
if(isalpha(keyword[i] == 0 ))
{
printf("Only use alpha\n");
return 1;
}
}
keyOk = 1;
}
}
while(keyOk == 0);
string cipherInput = GetString();
int cipherLength = strlen(cipherInput);
int j = 0;
for(int i = 0; i < cipherLength; i++)
{
if(isalpha(cipherInput[i]))
{
if(islower(keyword[j]))
{
if(islower(cipherInput[i]))
{
printf("%c", ((((cipherInput[i] - 97)+(keyword[j]-97))%26)+97));
}
else
{
printf("%c", ((((cipherInput[i] - 65)+(keyword[j]-97))%26)+65));
}
}
else
{
if(islower(cipherInput[i]))
{
printf("%c", ((((cipherInput[i] - 97)+(keyword[j]-65))%26)+97));
}
else
{
printf("%c", ((((cipherInput[i] - 65)+(keyword[j]-65))%26)+65));
}
}
j = i % cipherLength;
}
else
{
printf("%c", cipherInput[i]);
}
}
//printf("%s\n", keyword);
printf("\n");
}
GDB 输出,我不明白它的含义。通常它只是给我一个行号...
New LWP 31749]
Core was generated by `./vigenere'.
Program terminated with signal 11, Segmentation fault.
#0 __strlen_sse2_bsf () at ../sysdeps/i386/i686/multiarch/strlen-sse2-bsf.S:50
50 movdqu (%edi), %xmm1
【问题讨论】:
-
C?
string?也许int main(int argc, char* argv[])? -
您需要实际传递一个参数,例如
./vigenere blabla。否则argv[1]是NULL。您的代码应在访问argv[1]之前检查argc > 1。 -
另外,当您发布使用像
cs50.h这样的非标准标头的代码时,您应该发布该标头的内容,否则我们只是在猜测像string和GetString这样的东西. -
请注意
if(isalpha(keyword[i] == 0 ))中的非预期括号应为if (isalpha((unsigned char)keyword[i]) == 0)甚至if (!isalpha((unsigned char)keyword[i]))。不过,这不会导致崩溃。 -
<cs50.h>标头在这里相当常见(搜索[c] cs50.h的结果有 87 个)。假设typedef char *string;。不是很好的typedef,但这不是学生的错。
标签: c segmentation-fault cs50 vigenere