首页 > 解决方案 > 更改数组中的A字符串时出现C分段错误

问题描述

我有这个指向字符串的指针数组,它在 Main 函数上方定义为 public:

char *Code[]={"MAIN:  add r3,  LIST",
            "LOOP: prn #48",
            "lea STR, r6",
            "inc r6",
            "mov r3, K",
            "sub r1, r4",
            "bne END",
            "cmp val1, #-6",
            "bne %END",
            "dec K",
            "jmp %LOOP",
            "END: stop",
            "STR: .string “abcd”",
            "LIST: .data 6, -9",
            ".data -100",
            ".entry K",
            "K: .data 31"};

我编写了一个函数,假设查找 A 行中是否有一系列制表符和空格,如果有,则应更改字符串,以便只有一个空格或制表符:

void SpaceTabRemover()//function to make sure there are no two tabs or spaces following eachother
{
    int i,j=0,k=0; //i=which line we are at, j=which char of the line we ar at, k=placeholder for the last char which equal to space or tab
    for(i=0;i<sizeof(Code)/sizeof(Code[0]);i++)
    {
        while(Code[i][j])
        {
            if ((Code[i][j]==' '||Code[i][j]=='\t')&&(Code[i][j+1]==' '||Code[i][j+1]=='\t'))//checks if there is a sequence of tabs and spaces
            {
                Code[j][k++]=Code[i][j];
            }
            j++;
        }
        Code[j][k]='\0';
    }
}

我认为代码应该可以通过它的外观工作,除非我写错了并且我看不到它,

我的问题是当函数确实在 A 行中找到两个空格或制表符并尝试对字符串进行更改时,我收到了一个我以前从未见过的错误:

程序在 main.c.112 Code[j][k++]=Code[i][j] 处的 SpaceTabRemover() 中收到信号 SIGSEGV 分段错误

这个错误是什么意思,我该如何解决?

标签: csegmentation-faultarrayofstring

解决方案


arrya 的元素Code是指向字符串文字的指针,不允许修改。

在修改字符串之前,您必须将字符串复制到可修改的缓冲区。

#include <stdlib.h> // for malloc() and exit()
#include <string.h> // for strlen() and strcpy()

void SpaceTabRemover()//function to make sure there are no two tabs or spaces following eachother
{
    int i,j=0,k=0; //i=which line we are at, j=which char of the line we ar at, k=placeholder for the last char which equal to space or tab
    for(i=0;i<sizeof(Code)/sizeof(Code[0]);i++)
    {
        // allocate buffer and copy strings
        char* buffer = malloc(strlen(Code[i]) + 1); // +1 for terminating null-character
        if (buffer == NULL) exit(1); // check if allocation succeeded
        strcpy(buffer, Code[i]); // copy the string
        Code[i] = buffer; // assign the copied string to the element of array

        while(Code[i][j])
        {
            if ((Code[i][j]==' '||Code[i][j]=='\t')&&(Code[i][j+1]==' '||Code[i][j+1]=='\t'))//checks if there is a sequence of tabs and spaces
            {
                Code[j][k++]=Code[i][j];
            }
            j++;
        }
        Code[j][k]='\0';
    }
}

推荐阅读