【发布时间】:2017-04-12 19:21:48
【问题描述】:
我正在开发一个程序,要求用户输入一个单词以及用户想要从该单词中复制的字母数。该程序在我使用 Compile Online 时有效,但是当我在 Micrsoft Visual Studio 中运行该程序时,在我输入要复制的单词后程序冻结。我运行调试器,发现如下所示的错误。我认为,from googling,我正在写超过为我的数组预留的内存量?我应该使用 malloc 来解决这个问题吗?下面贴出错误和代码(链接到原始stackoverflow thread。
在 lab1113problem7.exe 中的 0x0FFB0BA0 (ucrtbased.dll) 处引发异常:0xC0000005:访问冲突写入位置 0x00B80000。
lab1113problem7.exe 中 0xFEFEFEFE 处的未处理异常:0xC00001A5:检测到无效的异常处理程序例程(参数:0x00000003)。
程序“[7196] lab1113problem7.exe”已退出,代码为 0 (0x0)。
程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *copywords(char *dest, const char *source, size_t n);
int main(void) {
char words[50];
char newwords[50];
int num;
for (;;) {
printf("Type a word, or type 'quit' to quit: ");
if (scanf("%49s", words) != 1) {
printf("Invalid input!\n");
return 0;
}
if (!strcmp(words, "quit")) {
printf("Good bye!\n");
return 0;
}
printf("Type the # of chars to copy: ");
if (scanf("%d", &num) != 1) {
printf("Invalid input!\n");
return 0;
}
copywords(newwords, words, num);
printf("The word was %s\n", words);
printf("and the copied word is %s\n", newwords);
}
}
char *copywords(char *dest, const char *source, size_t n) {
size_t i;
for (i = 0; i < n && source[i] != '\0'; i++) {
dest[i] = source[i];
}
dest[i] = '\0';
return dest;
}
【问题讨论】:
-
使用调试器更有效地帮助您找到问题。对于初学者来说,它到底是哪一行代码崩溃了。调试器告诉你。并使用调试器检查
num的值。然后继续继续逐行执行程序。 -
我没有发现任何问题。但是您确定这是您正在运行的实际代码吗?例如,如果将
printf("Yes, this is the actual code!\n");添加为main的第一条语句,然后运行程序,你会看到那个输出,并且程序仍然无法运行吗? -
@kaylum 只要我输入一个单词,调试器就会停止并抛出异常。
-
@Markovnikov 好吧,你已经知道了。此外,调试器不会抛出异常,您的程序会抛出调试器告诉您的异常。另外,异常是从代码的哪一部分引发的?查看“调用堆栈”窗口/窗格/区域。
-
@Markovnikov 是的,但是您可以从调试器中获取所谓的“堆栈跟踪”。这可以准确地告诉您哪一行代码触发了崩溃。显然,您还没有学会有效地使用调试器。请这样做。这将是美好的时光。