c - 我想知道为什么第36行会导致断言失败

标签 c

根据错误信息,“strStripped[k] = RemSpecial[i];”行导致调试断言失败。 表达式:c>=-1 && c <= 255

我不知道发生了什么。

我已经尝试自己解决这个问题了。但是,我只是一个初学者。这超出了我的范围。

感谢您提前提出意见。

#include <stdio.h>
#include <string.h>
#include <ctype.h>

char OnlyAlphabet(char RemSpecial[]);

int main()
{
char str[50];

printf("Insert the sentence to check the Palindrome: ");
scanf_s("$s", str);

printf("%s\n", OnlyAlphabet(str));

return 0;

}

char OnlyAlphabet(char RemSpecial[])
{
char strStripped[50];
int i;
int j = 0;
int k = 0;
for (i = 0; i < strlen(RemSpecial); i++)
{
    if (isalnum(RemSpecial[i]))
    {
        ***strStripped[k] = RemSpecial[i];***
        k++;
    }
}

strStripped[k] = '\0';

return strStripped;
}

最佳答案

您的代码存在一些问题:

  • 这一行:

    scanf_s("$s", str);
    

    需要改为:

    scanf_s("%49s", str);
    

    scanf() 需要格式说明符的 % 部分,而不是 $。最好使用 %49s 而不是简单地使用 %s,这样可以保护 str 免受缓冲区溢出的影响。我还建议使用 scanf() 代替,因为它更易于使用。

  • 您的函数 char OnlyAlphabet(char RemSpecial[]) 仅返回 char。您希望它是 char *,它将返回指向修改后的字符串 strStripped 的指针。

    但是,这意味着您无法在堆栈上分配此数组,例如:

    char strStripped[50];
    

    因为当函数返回时它会被解开,因此调用这个函数是不安全的。它只会返回在堆栈上分配的局部变量的地址,当函数返回时,该地址将消失。

    您需要在堆上分配一个指针,以便可以在程序中共享 strStripped。你可以这样做malloc .

    malloc() allocates requested memory on the heap, and returns a void* pointer to it.

    对于您的程序,可以这样实现:

    char *strStripped = malloc(strlen(RemSpecial)+1);
    

    它分配足够的内存块来容纳RemSpecial和空字节字符\0

    注意: malloc() 可能返回 NULL,需要在继续之前进行检查。您还需要free该内存以安全的方式位于程序末尾。

  • 您也不需要 strlen() 作为循环字符串的保护。您可以简单地循环直到找到 \0 字符。

    你的守卫可以是这样的:

    RemSpecial[i] != '\0'
    

您的程序修改为:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define STRSIZE 50

char *OnlyAlphabet(char RemSpecial[]);

int main(void) {
    char str[STRSIZE];
    char *result;

    printf("Insert the sentence to check the Palindrome: ");
    scanf("%49s", str);

    result = OnlyAlphabet(str);

    printf("%s\n", result);

    free(result);
    result = NULL;

    return 0;
}

char *OnlyAlphabet(char RemSpecial[]) {
    char *strStripped;
    int i, k = 0;

    strStripped = malloc(strlen(RemSpecial)+1);
    if (strStripped == NULL) {
        printf("Cannot allocate string\n");
        exit(EXIT_FAILURE);
    }

    for (i = 0; RemSpecial[i] != '\0'; i++) {
        if (isalnum(RemSpecial[i])) {
            strStripped[k] = RemSpecial[i];
            k++;
        }
    }

    strStripped[k] = '\0';

    return strStripped;
}

关于c - 我想知道为什么第36行会导致断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41867833/

相关文章:

c - 分代GC源代码

C scanf格式化

c++ - 静态编译过剩?

c - 使用 libevent 的异步 Redis 池

c - 使用 Eclipse IDE 作为我的编程语言的文本编辑器

c - 如何将宏调用函数转换为内核函数?

c - 如何计算闰年DAY?

c - 我如何在C中将指针的最右边位设置为1

c - ret2eax 的问题

C 程序 : converting an if statement code to a code which does not use logical, 关系运算符或选择结构(允许 NO 开关)