C 字符串指针函数 strdel

标签 c arrays function pointers cstring

谁能解释一下为什么我会收到“Segmentation fault...”以及如何修复这段代码?

#include<stdio.h>

int str_length(char *s) {
    int length = 0, i;
    for(i = 0; *s; i++) {
        s++;
    }
    return i;
}

char *strdel(char *s, int pos, int n) {
    int i;
    char *p, str[] = "";
    p = str;
    for(i = 0; i < str_length(s) - n + 1; i++)  {
        if(i >= pos) {
            *(p + i) = *(s + i + n);
        }
        else {
            *(p + i) = *(s + i);
        }
    }
    s = str;
    return s;
}

int main() {
    char *str = "abcdef";
    printf("str_lengh: %d\n", str_length(str));
    printf("strdel: %s\n", strdel(str, 1, 2));
    return 0;
}

我得到了这个输出:

str_lengh: 6
strdel: adef
Segmentation fault (core dumped)

另外,有没有更好的方法来创建一个函数: char *strdel(char *s, int pos, int n); 从位置 pos 删除的 n 个字符比我做的那个删除了 n 个字符?

最佳答案

我认为你在这里写满了堆栈......

char *strdel(char *s, int pos, int n) {
    int i;
    char *p, str[] = "";
    p = str; // p points to str which is "" and is on the stack with length 0.
    for(i = 0; i < str_length(s) - n + 1; i++)  {
        if(i >= pos) {
            *(p + i) = *(s + i + n); // now you are writing onto the stack past p
        }
        else {
            *(p + i) = *(s + i);// now you are writing onto the stack past p
        }
    }
    s = str; // now s points to space on stack
    return s; // now you return a pointer to the stack which is about to disapear 
}

每当你写过去的 p 时,你就会遇到未定义的行为。 UB 您正在写入尚未在堆或堆栈上分配的空间。

您可以编写一个仅适用于 s 的 strdel 版本。如果我对 strdel 的理解是正确的,那么就像这样:(粗略地说,未经测试!需要对 pos 和 n 进行边界检查)

char *strdel(char *s, int pos, int n) {
    char *dst = s + pos, *src = s + pos + n;
    while(*src) {
        *dst++ = *src++;
    }
    *dst = 0;
    return s;
}

关于C 字符串指针函数 strdel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19696338/

相关文章:

c - C 程序中的答案不正确,我缺少什么?

c - c中数组中的随机字符串

javascript - 使用 jquery 中的 data.split 函数从 csv 文件返回特定行

python - Pandas 更新对随后修改的附加值的更改

postgresql - 使用 %ROWTYPE 在 postgres 函数中循环数据时出现问题

python - 将bytearray从Python传输到C并返回

c - 需要帮助将文件内容扫描到指针数组中

php - 从标签列中的每个项目创建 div

javascript - 如何创建一个具有多维数组输入、转换它并输出新的多维数组的函数

c++ - 将类回调函数分配给结构?