2014-10-16 91 views
1

我使用libconfig.h從配置文件中讀取參數,但是我在打印函數內部/外部的值時遇到問題。使用libconfig.h字符串和字符集的問題

example.h文件

int get_config(); 

example.c

#include <stdio.h> 
#include <stdlib.h> 
#include <libconfig.h> 
#include "example.h" 

typedef struct Conf{ 
    int myInt; 
    const char *myString; 
}Conf; 

#define CONFIGFILE "./my.conf" 
Conf *config; 


int get_config(){ 
    config_t cfg; 
    config_init(&cfg); 

    if (!config_read_file(&cfg, CONFIGFILE)) { 
     fprintf(stderr, "%s:%d - %s\n", 
      config_error_file(&cfg), 
      config_error_line(&cfg), 
      config_error_text(&cfg)); 
     config_destroy(&cfg); 
     return(EXIT_FAILURE); 
    } 

    if(config_lookup_int(&cfg,"myInt", &config->myInt)){ 
     printf("myInt = %d\n", config->myInt); 
    } 

    if(config_lookup_string(&cfg,"myString", &config->myString)){ 
     printf("myString = %s\n", config->myString); 
    } 

    config_destroy(&cfg); 
    return 0; 
} 

int main(){ 
    config = (Conf*) malloc(sizeof(Conf)); 
    if(get_config() == EXIT_FAILURE){ 
     return 0; 
    } 
    get_config(); 

    printf("myInt = %d\n",config->myInt); 
    printf("myString = %s\n",config->myString); 

    return 0; 
} 

myInt值印刷內部/外部get_config()是相同的。對於myString,致電main()返回虛假字符,與之前打印的字符不同。

怎麼了?

+1

[在C中,你不應該使用'malloc'結果。](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – 2014-10-16 10:22:00

回答

1

libconfig manual

存儲由config_lookup_string()是由庫管理,在設置被破壞,或當設置的值更改自動釋放返回的字符串;該字符串不能被調用者釋放。

您的config_t cfg位於get_config的本地,在離開該功能後超出範圍。這意味着(a)你以後不能用config_destroy()正確地清理cfg和(b)cfg內的任何引用可能無法訪問,因爲堆棧空間已被覆蓋。

您可以在get_config中使用strdup製作一個字符串的副本。在這種情況下,在get_config的末尾銷燬cfg,就如同你fclose任何打開的本地文件一樣。稍後請注意free您的字符串。

另一種方法是將cfg設置爲main,並在程序的執行時間內保持活動狀態。作爲指針傳遞&cfgget_config,並在從main返回之前銷燬cfg。在這種情況下,只要cfg有效,字符串就會有效。

+0

對不起,我省略'config_destroy()',但這不是問題所在。運行它,我得到函數內的值(Ok),但是在main中只有int值是正確的。字符串顯示我虛假的字符(例如, e4)。 – user4129093 2014-10-16 11:12:15

+0

我的回答解決了這個問題:你的字符串,即需要存儲它的內存,不會「保持活着」足夠長的時間。你必須做一個副本(當原始字符串「死掉」時不要在意),或者讓擁有原始字符串的'cfg'在'main'中使'cfg'變量足夠長。 – 2014-10-16 11:17:15

+0

該字符串被存儲爲'Conf'中的指針。當它指向的內容不再有效時,指針就沒用了。這就是你的情況。 (嗯,這就是_probably_發生的事情;我沒有嘗試過,因爲我不想安裝'libconfig'。)'int'沒有這個問題。 – 2014-10-16 11:19:44