C语言中void cpy,在c中使用strncpy时出现分段错误

此代码应该用作vigenere密码。但是,在运行时,无论您输入什么输入,它都会出现分段错误。我正在为edx在线CS50课程写这篇文章。是否strncpy应该阻止分段错误发生,如果我告诉它复制适当的字符数量?在c中使用strncpy时出现分段错误

#include

#include

#include

#include

#include

int main(int argc, string argv[]) {

int result;

if (argc != 2) {

printf("Shame on you!\n");

return 1;

}

string key = argv[1];

string text = GetString();

string cpy_key = NULL;

//strncpy(cpy_key, key, strlen(key));

for (int i = 0, n = strlen(text); i < n; i++) {

strcat(cpy_key, key);

}

cpy_key[strlen(text)] = '\0';

// Main loop starts here

for (int i = 0, n = strlen(text); i < n; i++) {

result = text[i] + cpy_key[i];

if (isupper(text[i]) && (result > 'Z')) {

result = result - 26;

}

if (islower(text[i]) && (result > 'z')) {

result = result - 26;

}

if (isalpha(text[i])) {

printf("%c", result);

} else {

printf("%c", text[i]);

}

}

printf("\n");

return 0;

}

2016-01-24

Fluffy

+1

你为什么使用'strncpy()'?使用'strcpy()'或者如果你知道目标缓冲区的长度和源缓冲区的长度,确实也使用'memcpy()',除非字符串在循环内部改变,否则不要在循环中使用'strlen()'。 –

+0

@iharob使用strcpy()仍然会导致分段错误。此外,strlen()仅在循环开始时被调用一次,并且被保存为int n。 –

+0

在llp开始的时候这样做,它在我看来就像是'for'的条件。你在Linux上吗?或者mac?如果是这样,我建议[valgrind](http://www.valgrind.org),它应该可以帮助你快速发现问题。 –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值