簡體   English   中英

鏈式 strsep 給出分段錯誤 - C

[英]Chained strsep gives segmentation fault - C

我正在嘗試創建一個字符串數組,以准備將它們顯示在表格中。

所以我有一個 function 返回一個緩沖區字符串,其中包含一些掃描的 wifi 接入點的列表,我使用strsep將其拆分為"\n" ,然后再拆分為"\t"

循環運行良好,直到結束,當評估while參數((line = strsep(&buf, "\n")))時,它會給出SEGFAULT

每個@Jabberwocky 詢問的簡短說明性示例:

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

static int
wap_scan_count_lines(char*      wap_scan)
{
    int   line_amount = 0;
    char *scan = wap_scan;

    while(*scan)
    {
        if ('\n' == *scan){
            line_amount++;
        }
        scan++;
    }
    return line_amount;
}

int main() {

    char ***scan_result, *line=NULL, *item=NULL, *scan=NULL;
    scan = strdup("bssid / frequency / signal level / flags / ssid\n"
                  "a8:6a:bb:e2:d6:ef       5785    -47     [WPA-PSK-CCMP+TKIP][WPA2-PSK-CCMP+TKIP][WPS][ESS]       Fibertel WiFi114 5.8GHz");
    int wap_scan_size = wap_scan_count_lines(scan);
    scan_result = malloc(wap_scan_size * sizeof(**scan_result));
    int i = 0;
    int item_len = sizeof (*scan_result);

    while((line = strsep(&scan, "\n")) != NULL ) {
        if(i==0){
            i++;
            continue;
        }
        char **scan_line = calloc(5, item_len);
        int j = 0;
        while ((item = strsep(&line, "\t")) != NULL) {
            printf("%s\n", item);
            scan_line[j++] = strdup(item);
        }
        scan_result[i++] = scan_line;
    }
    return 0;
}

真正的 function 給我帶來了問題:

char *** wifi_client_get_wap_list(int *len)
{
    char ***scan_result;
    char *buf, *buf_free, *cmd, *line, *item;
    int ret, items_len;
    cmd = strdup("SCAN");
    ret = wpa_ctrl_command(cmd, NULL);
    if (ret < 0) goto error;

    cmd = strdup("SCAN_RESULTS");
    ret = wpa_ctrl_command(cmd, &buf); //RETURNS A STRING ON BUF ALLOCATED BY STRDUP
    if (ret < 0){
        free(buf);
        goto error;
    }

    *len = wap_scan_count_lines(buf); //NUMBER OF LINES IN THE SCAN RESULT
    scan_result = calloc(*len, sizeof(**scan_result));
    int i = 0, j;
    buf_free = buf;
    items_len = sizeof (*scan_result);

    while ((line = strsep(&buf, "\n"))){ //THIS GIVES THE SEGFAULT AT THE END
        // SKIP FIRST LINE WITH HEADERS
        if (i==0){
            i++;
            continue;
        }

        //if (strcmp(line, "") == 0) {
        //  break;   
        //}

       //EACH LINE HAS 5 VALUES (bssid, freq, level,flags,ssid)
        char **scan_line = calloc(5, items_len); 
        j = 0;
        printf("INNER STEPS:\n");
        while((item = strsep(&line, "\t"))){
            *(scan_line + j) = strdup(item);
            printf("%d ", j);
            j++;
        }
        *(scan_result + i) = scan_line;
        printf("\nSTEP: %d\n", i);
        i++;
    }

    free(buf_free);
    free(cmd);
    return scan_result;

    error:
    // @TODO: Handle error
    if (ret == -2) {
        printf("'%s' command timed out.\n", cmd);
    } else if (ret < 0) {
        printf("'%s' command failed.\n", cmd);
    }

    free(cmd);
    return NULL;
}

基於https://man7.org/linux/man-pages/man3/strsep.3.html問題是循環運行的時間比您希望的多,導致scan_result溢出。

文檔的相關部分是:

   The strsep() function returns a pointer to the token, that is, it
   returns the original value of *stringp.

   If *stringp is NULL, the strsep() function returns NULL and does
   nothing else.  Otherwise, this function finds the first token in
   the string *stringp, that is delimited by one of the bytes in the
   string delim.  This token is terminated by overwriting the
   delimiter with a null byte ('\0'), and *stringp is updated to
   point past the token.  In case no delimiter was found, the token
   is taken to be the entire string *stringp, and *stringp is made
   NULL.

wap_scan_count_lines 中,您計算以 '\n' 結尾的行數。

在以下 2 行中,您根據以“\n”結尾的行數分配 memory 來保存結果。

int wap_scan_size = wap_scan_count_lines(scan);
scan_result = malloc(wap_scan_size * sizeof(**scan_result));

但是,上面引用的strsep()文檔意味着在您的簡化示例中,第一個wap_scan_size次 strsep 被調用,在調用結束時,結果不會是 NULL 並且在調用期間掃描不會設置為 NULL。 下一次調用時,調用期間掃描將設置為 NULL,但結果不會是 NULL。 這意味着循環體將被執行wap_scan_size + 1 次,導致寫入超過scan_result的末尾。

至少有兩種可能的修復方法,具體取決於您是否真的要處理輸入末尾未由“\n”終止的任何行。

如果您確實需要處理這樣的行,這對我來說似乎更健壯,特別是考慮到您的簡化示例以這樣的行結尾,只需在scan_result中分配一個額外的條目:

scan_result = malloc((wap_scan_size + 1) * sizeof(**scan_result));

如果您非常確定不需要處理這些行,但這對我來說似乎不正確,請更改:

while((line = strsep(&scan, "\n")) != NULL ) {

for(line = strsep(&scan, "\n"); scan != NULL; line = strsep(&scan, "\n") ) {

暫無
暫無

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

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