我有一個結構聲明爲extern conf_t conf
。extern關鍵字和設置字符串變量
typedef struct {
int home_dir_len;
char *home_dir;
int key_file_len;
char *key_file;
unsigned int max_mem;
unsigned int runtime;
} conf_t;
我想通過下面的函數來設置它的變量,但只有整數值被設置,而不是字符串。
if (strcmp(tok1, "HOME_DIR") == 0) {
char *dir = strtok(NULL, &delim);
conf.home_dir_len = strlen(dir);
conf.home_dir = dir;
}
else if (strcmp(tok1, "KEY_FILE") ==0) {
char *key = strtok(NULL, &delim);
conf.key_file_len = strlen(key);
conf.key_file = calloc(conf.key_file_len +1, sizeof(char));
conf.key_file = key;
}
else if (strcmp(tok1, "MAX_MEM") ==0) {
conf.max_mem = atoi(strtok(NULL, &delim));
}
else if (strcmp(tok1, "RUNTIME") ==0) {
conf.runtime = atoi(strtok(NULL, &delim));
}
else {
perror("you shouldnt be here");
}
這是輸出:
conf.home_dir_len = 5 conf.home_dir = ' and more empty lines ' **This should be /tmp/** conf.key_file_len = 10 conf.key_file = 'nd more empty lines ' **this should be myfile.key** conf.max_mem = 10 conf.runtime = 10
能否請您解釋一下爲什麼,我該如何糾正呢?
您在這裏沒有真正顯示足夠的上下文。結構的定義是什麼?至少,你泄露了calloc調用的結果。 'sizeof(char)'是'1'。 –
如何編輯我的代碼沒有做到這一點,我添加了釋放calloc的第二部分,看它是否發揮了作用,但它沒有,因爲它們都仍然不正確 – cxzp