簡體   English   中英

segfault分配char數組的大小

[英]segfault on allocating size for a char array

我是編程新手,所以還不是很好。 但是我一直在打破我所犯的段錯誤的觀念。

基本上,我想擁有一個多線程可訪問字符存儲,可以從多個線程寫入並可以從一個線程讀取。

現在,由於緩沖區將顯示在屏幕上,所以我不想通過互斥來保護閱讀方面,因為該鎖會引起很高的爭用。

我想到的是函數中的靜態雙緩沖區,我向其中一個緩沖區寫入內容,然后在我調用read時,寫入緩沖區將被清空到讀取緩沖區中,並返回指向讀取緩沖區的指針。

這樣可以確保我可以安全地使用單個線程進行讀取,也可以使用多個線程進行寫入。

我無法實現清除或輸出緩沖區,因為無法使寫入正常工作。

下面是可編譯代碼,在這里我演示了我想要的東西,我已經注釋掉了互斥對象。 在為單行分配空間后,出現段錯誤。 如果更改緩沖區的逐步大小,它將在確切的段錯誤的行上更改。

我希望有人可以啟發我我做錯了什么!

#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嘗試從該地址讀取時,segfault就會出現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM