再Linux上使用vscode调试C代码时提示无法打开malloc.c文件

新手上路,请多包涵

题目描述

使用“%20”替换一个字符创中的空格

相关代码

我的代码是这样子的

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "malloc.h"
#define PLACESPACE "%20"
int main(void)
{
    char *replaceSpace(const char *str, int length);
    char *str = "This is test string!";
    char *newStr = NULL;
    newStr = replaceSpace(str, sizeof(str)); // 长度有EOF
    printf("%s\n", newStr);
    free(newStr);
    return 0;
}

char *replaceSpace(const char *str, int length)
{
    int spaceCount = 0; //空格总数
    // 记录空格
    while (*str != EOF)
    {
        // 遍历字符串字符
        if (*(str++) == ' ')
        {
            // 选择指针的位置再这里偏移
            spaceCount++;
        }
    }
    // 替换空格
    char *newStr = (char *)malloc(length + spaceCount*3); // 新字符串的存储位置
    newStr[0] = EOF;
    for (int i = 0; i < sizeof(newStr); i++)
    {
        // 循环,如果遇到空格便替换
        if (*str == ' ')
        {
            strcat(newStr, PLACESPACE);
            str++;
            i += 3;
            continue;
        }
        newStr[i] = *str;
        newStr[i + 1] = EOF;
        str++;
    }

    return newStr;
}

问题描述

VS就像是真样子报错
图片描述
gdb的描述是这样子的
图片描述

我不知道发生了什么,求解

阅读 6k
2 个回答

include "malloc.h" 改为 #include <malloc.h>

replaceSpace 中str指针在记录空格数后没有回恢复到字符串起始位置

建议:

const char *tmp = str;
// 记录空格
    while (*tmp != EOF)
    {
        // 遍历字符串字符
        if (*(tmp++) == ' ')
        {
            // 选择指针的位置再这里偏移
            spaceCount++;
        }
    }

新字符串分配的内存多了
// 替换空格
char newStr = (char )malloc(length + spaceCount*2); // 新字符串的存储位置

spaceCount*2 即可

Eg:
abc空格def空格g\0
替换后结果
abc%20def%20g\0

原来的一个字符变为三个,增加了两个,length中的长度包含原来的空格长度

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题