c - 为 char 数组分配大小时出现段错误

标签 c memory-management segmentation-fault buffer

我是编程新手,所以还不太擅长。但我一直因为遇到的段错误而伤透了脑筋。

基本上我想要一个多线程可访问的字符存储,我可以从多个线程写入并使用单个线程读取。

现在,由于缓冲区将显示在屏幕上,我不想通过互斥锁来保护读取方面,因为该锁会引起非常高的争用。

我想到的是函数中的静态双缓冲区,其中我写入一个缓冲区,然后一旦我调用读取,写入缓冲区将被清空到读取缓冲区中,并返回一个指向读取缓冲区的指针。

这确保我可以安全地使用单线程读取并使用多个线程写入。

我还没有实现清理或输出缓冲区,因为我无法使写入正常工作。

下面是可编译的代码,我在其中演示了我想要的内容,我已经注释掉了互斥体。 为单行分配空间后出现段错误。如果我更改缓冲区步长,它会在其发生段错误的行上发生变化。

我希望有人能告诉我我做错了什么!

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

char **message(char *msg, char mode, unsigned int *e) {
    //static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

    static unsigned int errflag = 0;

    static unsigned int in_ln = 0; //amount of lines in the in_buf

    static unsigned int in_bufsize = 0; // current amount of lines the in_buf can hold
    static unsigned int out_bufsize = 0; // current amountof lines the out_buf can hold

    static const unsigned int bufsize_step = 2; // step size to increase the buffersizes

    static char **in_buf;
    static char **out_buf;

    unsigned int strlength = 0;
    unsigned int i = 0, h = 0, j = 0;
    unsigned int lncount = 0; // count of the amount of lines in the input message 'msg'

    // return once errflag is set previously
    if (errflag != 0) {
        *e = errflag;
        return NULL;
    }
    // mutex to ensure thread safety
    /*
    if (pthread_mutex_lock(&mtx) != 0) {
        errflag = 1;
        return NULL;
    }
    */

    //write to in_buf
    if (mode == 'w') {

        strlength = strlen(msg) + 1;
        printf("\n-----------new call---------\n");

        for (i=0; i<strlength; i++) {
            if (msg[i] == '\n' || msg[i] == '\0') {
                printf("found newline or \\n char at %u, with length %u, store at offset %u\n", i, i-h, lncount + in_ln);
                // check if buffer has suffcient size to hold a new line
                if (lncount + in_ln >= in_bufsize) {
                    // increase buffer by a step
                    printf("realloc buf. from %u to %u\n", in_bufsize, in_bufsize + bufsize_step);
                    in_bufsize += bufsize_step;
                    in_buf = realloc(in_buf, in_bufsize * sizeof(char *));
                    if (in_buf == NULL) {
                        errflag = 3;
                        *e = errflag;
                        goto end;
                    }
                }
                // allocate memory for the new line
                printf("alloc new line %u to %u\n", lncount + in_ln, (i - h + 1));
                in_buf[lncount + in_ln] = realloc(in_buf[lncount + in_ln] ,(i - h + 1) * sizeof(char));
                if (in_buf[lncount + in_ln] == NULL) {
                    errflag = 4;
                    *e = errflag;
                    goto end;
                }

                // put the line into the buffer
                for (j=0; h+j<i; j++) {
                    printf("%c", msg[h+j]);
                    in_buf[lncount + in_ln][j] = msg[h+j];
                }
                printf("\n");
                in_buf[lncount + in_ln][j] = '\0';

                printf("string %u is %s\n", lncount + in_ln, in_buf[lncount + in_ln]);
                h = i + 1;
                lncount++;
            }
        }

        in_ln += lncount;

    // append in_buf to out_buf, clean in_buf
    } else if (mode == 'r') {
        printf("realloc out_buf to %u\n", out_bufsize + in_ln);
        out_buf = realloc(out_buf, (out_bufsize + in_ln) * sizeof(char *));
        if (out_buf == NULL) {
            errflag = 4;
            *e = errflag;
            goto end;
        }

        printf("copying pointers...\n");
        for (i=0; i<in_ln; i++) {
            out_buf[i + out_bufsize] = in_buf[i];
            printf("copying %u. %s -> %u. %s\n", i + out_bufsize, out_buf[i + out_bufsize], i, in_buf[i]);
            in_buf[i] = NULL;
        }

        out_bufsize = out_bufsize + in_ln;
        in_ln = 0;
    // cleanup
    } else if (mode == 'c') {
        lncount = 0;
    }

    end: 
    /*
    if (pthread_mutex_unlock(&mtx) != 0) {
        errflag = 1;
        return buf;
    }
    */

    printf("in_buf: size %u\n", in_ln);
    for (i=0; i<in_ln; i++) {
        printf("%u. %s\n", i, in_buf[i]);
    }

    printf("out_buf: size %u\n", out_bufsize);
    for (i=0; i<out_bufsize; i++) {
        printf("%u. %s\n", i, out_buf[i]);
    }
    return out_buf;
}


int main() {
    unsigned int error;
    message("test test\n", 'w', &error);
    message(NULL, 'r', &error);
    message("test test2", 'w', &error);
    message("test test3", 'w', &error);
    message("test test4", 'w', &error);
    message(NULL, 'r', &error);
    message("test test5", 'w', &error);
    message("test test6", 'w', &error);
    message(NULL, 'r', &error);
    message("test test7", 'w', &error);
    message("test test8", 'w', &error);
    message(NULL, 'r', &error);
    message("test test9", 'w', &error);
    message("test test10", 'w', &error);
    message("test test11", 'w', &error);
    message("test test12", 'w', &error);
    message("test test13", 'w', &error);
    message("test test14", 'w', &error);

    message("lndsdss1\nln2\nln3\nln4\nln5\nln6\nln7\nln8\nln9\nln10\nln11\nln12\nln13\nln14\nln15\nln16\nln17\n", 'w', &error);

    exit(0);
}

最佳答案

补充 WhozCraig 的评论。您尝试使用 in_buf 作为指向指针的指针数组,而 in_buf 是一个静态变量。因此,in_buf 被初始化为NULL (0)。

如果您阅读 realloc 的定义,如果传递的内存地址为0,则其行为类似于malloc

因此,现在您有一个已分配内存的指针数组,并且它的第一个元素也指向相同的地址,因为 in_bufin_buf[0] 本质上是相同的地址。

因此,in_buf[0] 指向有效的已分配内存位置,但 in_buf[1] 指向 in_buf[n-1] 持有垃圾值,因为 malloc 不会将内容设置为 0,这与 calloc 不同。当您从 in_buf[0] 移至 in_buf[1] 时,它持有无效的内存地址,并且当 realloc 尝试从该地址读取时,会发生段错误。

关于c - 为 char 数组分配大小时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26251659/

相关文章:

c - 如何访问结构内部的 union ?

c - 可变数组大小的段错误

android - 如何制作 RAM 内存为 'eats' 的 Android 应用程序

Linux 中的 C 段错误(核心转储)错误

iphone - iOS(Monotouch)应用程序在 viewWillAppear 上崩溃

c - 为什么这段代码只返回我的数据集中的每隔一个坐标?

c++ stringstream到不同类型的变量

c - 在 MPI_Recv 写入后释放数组

memory-management - Google Play 服务在我的应用程序中消耗更多 RAM

c++ - std::string 的 type_traits 段错误