截断字符串导致分段错误

Truncating string causes segmentation fault

我想用 C 编写一个函数,将输入字符串截断为 32 个字符,但下面的代码给出了分段错误。谁能解释一下为什么会这样?

void foo (char *value){
    if (strlen(value)>32) {
        printf("%c\n", value[31]); // This works
        value[31] = '[=10=]';          // This seg faults
    }
}

如果你这样调用你的函数:

char str[] = "1234567890123456789012345678901234567890";
foo(str);

它将正常工作。但是如果你这样称呼它:

char *str = "1234567890123456789012345678901234567890";
foo(str);

这可能会导致段错误。

这里的区别在于前一种情况下str是一个char数组,而后一种情况下str是一个指向字符串常量的指针。字符串常量通常位于内存的只读部分,因此尝试修改它会导致核心转储。

你的程序应该是这样的:

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

void foo(char **value) {
    if (strlen(*value)>32) {
        printf("%c\n", (*value)[32]);
        (*value)[32] = '[=10=]'; // You want the string length to be 32, so set 32th character to '[=10=]' so 32 characters will be from 0 to 31
    }
}

int main() {
    char *str;
    str = malloc(100); // Change 100 to max possible length of string user can enter

    printf("Enter string : ");
    scanf("%s", str);

    foo(&str);

    printf("Truncated string is %s\n", str);

    free(str);

    return 0;
}