简体   繁体   English

在C中访问和修改字符串(char *)数组时出现段错误

[英]Segmentation fault in accessing & modifying string (char*) array in C

I've been getting segmentation faults (with gdb printing "??" on backtraces) on a program I'm trying to compile for a while now and after trying many things (such re-programming a data structure I used which should work now) I still kept getting segfaults although now it gave me a line (which I added a comment onto here). 我一直在尝试编译一段时间的程序上尝试分段,并在尝试了许多方法(例如重新编程我现在使用的数据结构)后遇到分段错误(gdb在回溯线上打印“ ??”) )我仍然不断遇到段错误,尽管现在它给了我一行(我在此处添加了评论)。

getMains() is ran multiple times to tokenize different lines from the same file. 多次运行getMains()来标记同一文件中的不同行。

I wanted mains to be an array of size 4 but when passing it as "char * mains[4]" II got a compile error for trying to pass it an array (*)[4] which I've never dealt with beforehand (Just started using C). 我希望mains是一个大小为4的数组,但是当将其作为“ char * mains [4]”传递时,II尝试将其传递给一个数组(*)[4]时遇到了编译错误,而我之前从未处理过(刚开始使用C)。 I'm assuming maybe that could be a problem if I try to access any part that wasn't used, but the problem happens while initializing the indices of the array. 我假设如果尝试访问未使用的任何部分,可能会出现问题,但问题是在初始化数组的索引时发生的。

The code I'm trying to get to work, where the "char *** mains" argument is taking in a &(char **) from a separate function "runner" which I want to be edited so I can look at its contents in "runner": 我正在尝试使用的代码,其中“ char *** mains”参数从单独的函数“ runner”中获取一个&(char **),我希望对其进行编辑,以便于查看“跑步者”中的内容:

bool getMains(FILE * file, char *** mains)
{
    char line[256];
    int start = 0;
    char * token;
    const char * mainDelim = "\t \n\0", * commDelim = "\n\t\0";

    if(fgets(line, sizeof(line), file) == NULL)
        return false;

    while(line[0] == '.')
        if(fgets(line, sizeof(line), file) == NULL);
            return false;

    if(line[0] == '\t' || line[0] == ' ')
    {
        (*mains)[0] = " ";
        start = 1;
    }

    token = strtok(line, mainDelim);
    int i;
    for(i = start; token != NULL; ++i)
    {
        (*mains)[i] = strdup(token); // <- gdb: Segmentation Fault occurs here

        if(i % 3 == 2)
            token = strtok(NULL, commDelim);
        else
            token = strtok(NULL, mainDelim);
     }

     free(token); // Unsure if this was necessary but added in case.
     return true;
}


/* Snippet of code running it... */
void runner(FILE * file) {
    char ** mains;
    if(!getMains(*file, &mains))
        return;
    while(strcmp(mains[1], "END") != 0){
        /* do stuff lookinig through indices 0, 1, 2, & 3 */
        if(!getMains(*file, &mains))
            break;
    }
}

Any tips on this or just generally safely modifying arrays through other functions? 关于此的任何提示还是通过其他功能通常可以安全地修改数组?

Should I change getMains() into "getMains(FILE * file, char ** mains[4]);" 我应该将getMains()更改为“ getMains(FILE * file,char ** mains [4]);” and pass it a &"char * mains[4]") for it to be a set size as wanted? 并通过一个&“ char * mains [4]”)使其成为所需的设置大小? Or would that also produce errors? 还是会产生错误?

You need to allocate memory for mains, it should look like this: 您需要为市电分配内存,它应如下所示:

char ** mains;
mains = malloc(some number N * sizeof(char*));

You need something like this if you don't use strdup, which allocates the memory for you: 如果不使用strdup,则需要这样的东西,它会为您分配内存:

for (int i = 0; i < N; ++i) {
  mains[i] = malloc(some number K);
}

In all cases, do not forget to call free on every pointer you received from malloc or strdup . 在所有情况下,请不要忘记对从mallocstrdup收到的每个指针进行free调用。 You can skip this part if the program ends right after you would call free . 如果程序在调用free之后立即结束,则可以跳过此部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM