进程已完成,退出代码为 138 CLion

问题描述 投票:0回答:1

我想在 C 中实现一个简单的函数,用另一个字符串替换一个字符串,但我不确定为什么会出现以下错误。我是指针新手

错误提示

Process finished with exit code 138 (interrupted by signal 10:SIGBUS)

我做了一些研究,发现它与缓冲区溢出有关,但我不明白为什么会在这里发生。

我正在使用最新版本的 CLion 来编译和运行我的程序

void censor(char *s, const char *search, const char *replace) {
    char *t = s;
    const char *temp = search;
    char *start = NULL;
    _Bool dirty = 0;

    while (*t && *temp) {
        if (*t != *temp && !dirty) {
            t++;
        } else if (*t == *temp) {
            if (start == NULL)
                start = t;

            t++;
            temp++;
            dirty = 1;
        } else {
            temp = search;
            dirty = 0;
            start = NULL;
        }
    }

    if (*temp == '\0') {
        while (*search && start) {
            *start++ = *replace++;
            search++;
        }
    }
}
c pointers
1个回答
0
投票

这是正确的,错误 138 通常表示程序导致总线错误,在类 Unix 操作系统中,这是由硬件引发的故障,通知未与可寻址内存边界对齐的非法内存访问。这显示了缓冲区溢出或访问 CPU 无法物理解决的内存问题。

原因可能是未初始化的指针或对已释放内存的访问,或者可能是替换字符串比搜索字符串长...

这是代码的更安全版本

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

void censor(char *s, const char *search, const char *replace) {
    char *found = strstr(s, search);
    if (found) {
        // Allocate memory for the new string
        size_t newSize = strlen(s) - strlen(search) + strlen(replace) + 1;
        char *newString = (char *)malloc(newSize);
        
        if(newString) {
            // Copy the part before the found search string
            size_t prefixLength = found - s;
            strncpy(newString, s, prefixLength);

            // Copy the replace string
            strcpy(newString + prefixLength, replace);

            // Append the rest of the original string after the search string
            strcpy(newString + prefixLength + strlen(replace), found + strlen(search));

            // Now copy the new string back to s
            strncpy(s, newString, newSize - 1);
            s[newSize - 1] = '\0';

            // Free the allocated memory
            free(newString);
        }
    }
}

int main() {
    char str[50] = "I like cats, because cats are great.";
    censor(str, "cats", "dogs");
    printf("%s\n", str); // Output should be: "I like dogs, because dogs are great."
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.