簡體   English   中英

字符串截斷會導致分段錯誤

[英]Truncating string causes segmentation fault

我想用C編寫一個將輸入字符串截斷為32個字符的函數,但是下面的代碼給我一個分段錯誤。 誰能解釋為什么會這樣?

void foo (char *value){
    if (strlen(value)>32) {
        printf("%c\n", value[31]); // This works
        value[31] = '\0';          // 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] = '\0'; // You want the string length to be 32, so set 32th character to '\0' 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM