2016-08-22 53 views
-1

過去,我不明白是什麼導致段錯誤後的第一輪如下:動態結構數組調整大小時參考

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

struct query_param { 
    char *key; 
    char *val; 
}; 

void extract_params(struct query_param **query_params, char *query_string, 
        size_t *query_params_len) { 
    char *token, *key; 

    while (query_string != NULL) { 
    token = strsep(&query_string, "&"); 
    key = strsep(&token, "="); 

    *query_params = realloc(*query_params, (*query_params_len + 1) * 
               sizeof(struct query_param)); 


    query_params[*query_params_len]->key = malloc(strlen(key)); 
    query_params[*query_params_len]->val = malloc(strlen(token)); 

    memcpy(query_params[*query_params_len]->key, key, strlen(key)); 
    memcpy(query_params[*query_params_len]->val, token, strlen(token)); 

    (*query_params_len)++; 
    } 
} 

int main(int argc, char **argv) { 
    char *query_string = "foo=bar&baz=boo&zip=zap"; 
    size_t query_params_len = 0; 
    struct query_param *query_params = NULL; 
    extract_params(&query_params, query_string, &query_params_len); 
    return 0; 
} 

將第一鍵值對的結構工作正常,但在second malloc正在造成麻煩

Valgrind的信息:

==15319== Memcheck, a memory error detector 
==15319== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al. 
==15319== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info 
==15319== Command: ./a.out 
==15319== 
==15319== 
==15319== Process terminating with default action of signal 11 (SIGSEGV) 
==15319== Bad permissions for mapped region at address 0x4008DF 
==15319== at 0x4EC1A0B: strsep (in /lib64/libc-2.23.so) 
==15319== by 0x4006C0: extract_params (foo.c:15) 
==15319== by 0x400848: main (foo.c:36) 
==15319== 
==15319== HEAP SUMMARY: 
==15319==  in use at exit: 0 bytes in 0 blocks 
==15319== total heap usage: 0 allocs, 0 frees, 0 bytes allocated 
==15319== 
==15319== All heap blocks were freed -- no leaks are possible 
==15319== 
==15319== For counts of detected and suppressed errors, rerun with: -v 
==15319== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) 

Valgrind的運行後,仍然沒有得到關於該問題的抓地力。尤其是堆總結對我來說沒有任何意義。運行malloc 3次後如何分配0字節?

乾杯!

+1

沒有錯誤檢查,沒有[mcve],沒有細節。看[問]! – Olaf

+0

你可以用'gcc -g'(並且沒有'-O ...'標誌)編譯它,並通過'valgrind'運行它。如果你不理解'valgrind'的輸出,那麼把它複製粘貼到問題上。 – pts

+0

感謝您的輸入。運行valgrind之後,我比以前更加困惑:D – grafoo

回答

3
query_params[*query_params_len]->blah 

query_params不是數組指針的,也不是一個指向數組指針的的第一個元素。它是指向結構數組的第一個元素的指針。你想要這個

(*query_params)[*query_params_len].blah 
+0

感謝您直接點! – grafoo

2

在@ n.m中指出的問題還有幾個問題。答案(query_params「指向指向陣列結構的第一個元素的指針」)。

char *query_string = "foo=bar&baz=boo&zip=zap"; 

聲明query_string作爲指針以一個常量字符串文字,但後來的程序必須修改存儲器指出由於使用的strsep()。你應該聲明數組作爲常量字符串的副本:

char query_string[] = "foo=bar&baz=boo&zip=zap"; 

此外,當您嘗試複製令牌,你應該遵循@約翰布林建議,並使用strdup()或至少採取'\0'終止考慮。

此外,你應該檢查所有庫函數的返回值,並在最後釋放分配的內存。

+0

所有的建議都非常感謝,我會很樂意將它們考慮在內,但@n.m。仍然回答我最初的要求。非常感謝,但! – grafoo

+0

@grafoo不客氣,我同意選擇。 –