简体   繁体   English

segfault分配char数组的大小

[英]segfault on allocating size for a char array

I am new to programming so I am not that good yet. 我是编程新手,所以还不是很好。 But I have been breaking my head of a segfault I have been getting. 但是我一直在打破我所犯的段错误的观念。

basically I want to have a multithreaded accesible character storage which I can write to from multiple threads and read from with a single thread. 基本上,我想拥有一个多线程可访问字符存储,可以从多个线程写入并可以从一个线程读取。

Now since a the buffer will be displayed on screen I didn`t want to protect the reading aspect by mutex because that lock would get a very high contention. 现在,由于缓冲区将显示在屏幕上,所以我不想通过互斥来保护阅读方面,因为该锁会引起很高的争用。

What I thought about is a static double buffer in function where I write to one buffer and then once I call the read the write buffer will be emptied into the read buffer and it returns a pointer to the read buffer. 我想到的是函数中的静态双缓冲区,我向其中一个缓冲区写入内容,然后在我调用read时,写入缓冲区将被清空到读取缓冲区中,并返回指向读取缓冲区的指针。

This ensures that I can safely read with a single thread and write with many. 这样可以确保我可以安全地使用单个线程进行读取,也可以使用多个线程进行写入。

I have not implemented the cleanup or the output buffer since I cannot get the writing to work correctly. 我无法实现清除或输出缓冲区,因为无法使写入正常工作。

Below is compileable code where I demonstrate what I want, I have commented out the mutexes. 下面是可编译代码,在这里我演示了我想要的东西,我已经注释掉了互斥对象。 I get a segfault after allocating space for a single line. 在为单行分配空间后,出现段错误。 If I change my buffer stepsize it changes on what line it exactly segfaults. 如果更改缓冲区的逐步大小,它将在确切的段错误的行上更改。

I hope somebody can enlighten me on what I am doing wrong! 我希望有人可以启发我我做错了什么!

#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);
}

Adding on to WhozCraig's comment. 添加到WhozCraig的评论中。 You are trying to use in_buf as an array of pointers to pointers, and in_buf is an static variable. 您尝试将in_buf用作指向指针的数组,并且in_buf是静态变量。 Hence, in_buf is initialized to NULL (0). 因此,in_buf初始化为NULL (0)。

If you read the definition of realloc , if the memory address passed is 0, it will act like malloc . 如果您阅读了realloc的定义,则如果传递的内存地址为0,它将像malloc一样工作。

Hence now you have a array of pointers which has allocated memory and its first element is also pointing to the same address because in_buf and in_buf[0] is essentially the same address. 因此,现在您有了一个分配了内存的指针数组,并且它的第一个元素也指向相同的地址,因为in_bufin_buf[0]本质上是相同的地址。

Hence, in_buf[0] is pointing to a valid allocated memory location, however in_buf[1] to in_buf[n-1] is holding garbage value as malloc does not set the content to 0, unlike calloc. 因此, in_buf[0]指向有效的已分配内存位置,但是in_buf[1]in_buf[n-1]保持垃圾值,因为malloc不会将内容设置为0,这与calloc不同。 When you move beyond in_buf[0] to in_buf[1] , it holds an invalid memory address, and when realloc tries to read from that address, segfault occours. 当您从in_buf[0]移到in_buf[1] ,它持有一个无效的内存地址,并且当realloc尝试从该地址读取时,segfault就会出现。

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

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