You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中write access violation含义、解决及最长公共前缀代码排查

C语言最长公共前缀函数的写入访问错误问题

我是C语言纯新手,之前用的都是Visual Basic、C#这类不用操心底层细节的语言。最近开始学指针,正在通过LeetCode题目练习。

题目要求:编写函数找出字符串数组中的最长公共前缀,若不存在公共前缀则返回空字符串""。

我的尝试代码:

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

char* longestCommonPrefix(char** strs, int strsSize) {
    if (strsSize == 1) return strs[0];

    if (strs[0] == "") return "";

    char* result = strs[0];
    size_t result_length = strlen(result) - 1;
    char* result_end = strs[0] + result_length;

    for (size_t i = 1; i < strsSize; ++i) {
        
        size_t length = strlen(strs[i]) - 1;
        
        if (length < 1) return "";
        
        if (length < result_length) {
            result_end = strs[0] + length;
            result_length = length;
        }

        char* temp1 = result;
        char* temp2 = strs[i];

        while (*temp1 == *temp2 && temp1 < result_end) {
            ++temp1;
            ++temp2;
        }

        if (temp1 < result_end) {
            result_end = temp1 - 1;
            result_length -= strlen(result_end) - 1;
        }
    }

    *(result_end + 1) = '\0';
    
    return result;
}


int main(int argc, char* argv[]) {
    char* a[3];
    a[0] = "flower";
    a[1] = "flight";
    a[2] = "flow";

    char* b = longestCommonPrefix(a, 3);
    printf(b);
}

为什么在语句*(result_end + 1) = '\0';处会出现write access violation错误?我搜索后了解到C字符串是只读的,想请教具体原因是什么,有什么解决方法?另外也欢迎提供C语言的通用技巧,谢谢。

编辑说明:
感谢@Chris提供的解决方案,以下是修改后可正常运行的代码,同时也融入了@@WeatherVane提供的C语言技巧:

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

char* longestCommonPrefix(char** strs, int strsSize) {
    if (strsSize == 1) return strs[0];

    if (strs[0][0] == 0) return "";

    char* result = _strdup(strs[0]);
    size_t result_length = strlen(result) - 1;
    char* result_end = strs[0] + result_length;

    for (size_t i = 1; i < strsSize; ++i) {

        char* str = _strdup(strs[i]);
        
        size_t length = strlen(str) - 1;
        
        if (length < 1) return "";
        
        if (length < result_length) {
            result_end = str + length;
            result_length = length;
        }

        char* temp = result;

        while (*temp == *str && temp < result_end) {
            ++temp;
            ++str;
        }

        if (temp < result_end) {
            result_end = temp - 1;
            result_length -= strlen(result_end) - 1;
        }
    }

    *(result_end + 1) = '\0';
    
    return result;
}


int main(int argc, char* argv[]) {
    char* a[3];
    a[0] = "flower";
    a[1] = "flight";
    a[2] = "flow";

    char* b = longestCommonPrefix(a, 3);
    printf(b);
}

内容的提问来源于stack exchange,提问作者OldCrow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:53:12