c - 用其他子字符串替换字符串的子字符串时出现段错误

标签 c string segmentation-fault

我有字符串“{”1”:“[4,11,14,19,20,18,27]”}“。我想把它改成 "{\"1\":\"4,11,14,19,20,18,27\"}"。

下面是我的代码:

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

char *replace (char *this, char *withthat, char *inthis) {
    char *where = inthis;

    while ((where = strstr(where, this))) {
        memcpy(where, withthat, strlen(withthat));
        memmove(where+strlen(withthat),where+strlen(this), strlen(where+strlen(this))+1);
    }
    return inthis;
}

int main(void) {
    char string[] = "{&quot;1&quot;:&quot;[4,11,14,19,20,18,27]&quot;}";
    printf("%s\n", replace("&quot;", "\\\"", string));
    printf("%s\n", replace("\"[" , "\"", string));
    printf("%s\n", replace("]\\" , "\\", string));
    printf("%s\n", replace("{" , "\"{", string));
    printf("%s\n", replace("}" , "}\"", string));
    return 0;
}

我收到最后两次替换调用的错误。我的运算符(operator)是 {\"1\":\"[4,11,14,19,20,18,27]\"} {\"1\":\"4,11,14,19,20,18,27]\"} {\"1\":\"4,11,14,19,20,18,27\"} 段错误

我尝试使用 gdb,但无法找到错误的根本原因。它在某种程度上与 memcopy 有关,但无法理解。如果有人能帮助我,那就太好了。提前致谢。

最佳答案

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

char *replace (char *old, char *new, char *buff) {
    char *ptr;
    size_t oldlen = strlen(old);
    size_t newlen = strlen(new);

    for(ptr=buff; ptr = strstr(ptr, old); ptr += newlen) {
        memmove(ptr+newlen, ptr+oldlen, strlen(ptr+oldlen)+1);
        memcpy(ptr, new, newlen);
    }
    return buff;
}

int main(void) {
    char string[1234] = "{&quot;1&quot;:&quot;[4,11,14,19,20,18,27]&quot;}";
    printf("%s\n", replace("&quot;", "\\\"", string));
    printf("%s\n", replace("\"[" , "\"", string));
    printf("%s\n", replace("]\\" , "\\", string));
    printf("%s\n", replace("{" , "\"{", string));
    printf("%s\n", replace("}" , "}\"", string));

    return 0;
}

最后两个替换“{}”包含其自身。这会导致原始字符串在同一位置重新扫描,重新匹配+重新替换。于无穷。 ptr+=newlen 避免了这种情况。

关于c - 用其他子字符串替换字符串的子字符串时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7843622/

相关文章:

CppCheck 警告 : expression depends on order of evaluation in x = x |= (1 << 3)

java - 如何从字符串输入实现 HashMap

c++ - 特定值的段错误

c - 段错误spoj协助

c - C 中指向 void 指针的指针 - 我可以使用 void** 进行基本的多态性吗?

c - DAQmxReadAnalogScalarF64 到底做什么?

在c中创建顺序子进程

java - 如何使用 Dozer 将字符串值映射到字符串列表?

string - Lua - 检测字符串是否包含密码的有效字符

c++ - 试图在构造函数中的 `glm::cross` 处初始化我的类段错误