调试断言失败错误,字符数组终止为null

Debug Assertion failed error with null terminated character array

本文关键字:数组 终止 null 字符 断言 失败 错误 调试      更新时间:2023-10-16

当我试图编译底层代码时,试图进行赋值,但我得到了以下调试断言失败的存根:

文件:f:\dd\vctools\crt\crtw32\convert\istype.c

线路:56

压缩c>=-1&amp;c<=255

这个错误消息似乎出现了几个问题。我甚至没有f驱动器或目录,除非在isctype.c程序中计算这一行,否则我的代码中没有56行。

目的是统计用户输入的单词数量。事先检查空格以及null终止字符。

以下代码已根据其他用户的评论进行了修复

#include <stdafx.h>
#include <iostream>
#include <string.h>
#include <cctype>
using namespace std;
int wordCount(int size, char wordArray[]);
int main(){
    const int SIZE = 100;
    char wordArray[SIZE];
    cout << "What is the string you wish to enter? ";
    cin.getline(wordArray, sizeof(wordArray));
    cout << "The number of words entered is: " << wordCount(strlen(wordArray), wordArray) << endl;
}
int wordCount(int size, char wordArray[]){
    int charCount = 0, wordCount = 0;
    //counts the number of words in the entered string
    for (int i = 0; wordArray[i] != ''; i++){
        if (isalnum(wordArray[i])){
            charCount++;
            if (isspace(wordArray[i + 1])){
                charCount = 0;
                wordCount++;
            }
        }
    }
    return wordCount;
}

此代码:

if (isspace(wordArray[i] && isspace(wordArray[i + 1]))){

有几个问题。您的方括号放错了位置,所以使用布尔参数调用issspace

此外,您应该从strlen中获取字符串的大小,此时您正在循环通过字符串的末尾。发生断言可能是因为您正在向isspace传递无效的char值(例如负数)。

编辑:另请注意下一行:

wordArray[i] = wordArray[i++];

不会做你想做的事。您希望将字符串的其余部分移回一个,而不仅仅是将一个字符复制到另一个字符。

收到此错误消息的原因是isspace()接受整数值(int),但对字符(通常为char类型)进行操作。您必须传递一个未初始化的负值,该负值在isspace()处理的域之外。传递的值不正确,ispace()实现会温和地通知您软件中存在此错误。库必须是在有f:驱动器的计算机上编译的。该实现确实有超过56行代码。

此外

使用wordCount(strlen(wordArray), wordArray)而不是传递SIZE。否则,您将读取未初始化的值,这是不好的。

使用break代替run = false,并将while替换为while(1)。此外,这个循环很可能并没有达到你认为的效果。您只是在用第二个字节覆盖第一个字节。您可能希望将所有字符向左移动。

在上一个循环中,迭代直到达到空字节(''),而不是达到size,因为这也是不正确的。注意,该字符串现在可能小于size;也许CCD_ 17根本不应该是一个参数。。。

考虑到这些问题,这里有一种解决问题的替代方法,它不需要修改原始字符串。

int count_words(const char *s) {
    int count = 0;
    bool in_word = false;
    while (*s != '') {
        if (isspace(*s)) {
            in_word = false;
        }
        else if (in_word == false) {
                count += 1;
                in_word = true;
        }
        ++s;
    }
    return count;
}

此断言错误来自C运行库内部。据推测,它是由一个有F驱动器的人建造的。行号在源代码中。

断言的原因是您试图测试字符类型中是否有无效字符。最有可能的候选者是字符串结尾的null终止符。

您不应该传入大小,而是使用strlen()来查找它。这样您就不会遇到null。

for (int i = 0; i < strlen(wordArray); i++) { ...

这3个循环中的每一个都有缺陷,不会按照注释所说的去做。您应该先解决以上两个问题,然后看看是否可以调试代码。