[英]why my variable's value changes (i noticed when using debugger that the value changed)?
[英]Why my variable changes its value when I am not changing it? C
我必須閱讀文件上的一些配置才能完成大學項目。 在我的 read 函數中,我使用一個結構來存儲配置,但是,我不知道為什么,其中一個變量在讀取下一個參數時會改變它的值。
struct client_config {
char name[20]; // en teoria son 6 + '\0'
char MAC[12];
char server[20];
int UDPport;
};
void read_software_config_file(struct client_config *config) {
FILE * conf;
conf = fopen(software_config_file, "r");
if (conf == NULL) {
fprintf(stderr, "Error obrir arxiu");
exit(-1);
}
char word[1024];
int i = 0;
fscanf(conf, "%s", word);
// No es la millor manera de fer-ho...
// pero ja que suposem que el fitxer es correcte
fscanf(conf, "%s", word);
// Ens saltem les comprovacions
strcpy(config->name, word);
fscanf(conf, "%s", word);
fscanf(conf, "%s", word);
strcpy(config->MAC, word);
printf("%s this is config->mac after first read \n", config->MAC);
fscanf(conf, "%s", word);
fscanf(conf, "%s", word);
strcpy(config->server, word);
printf("%s this is config->mac after next read \n", config->MAC);
fscanf(conf, "%s", word);
fscanf(conf, "%s", word);
config->UDPport = atoi(word);
fclose(conf);
}
輸出:
89F107457A36 這是第一次讀取后的 config->mac(這是正確的)
89F107457A36localhost 這是 config->mac after next read(這是不正確的)
我正在閱讀的文件是這樣的:
Nom SW-01
MAC 89F107457A36
Server localhost
Server-port 2019
MAC
字段中沒有用於終止'\\0'
空間。
當您第一次復制到MAC
字段時, printf
'\\0'
在server
字段中找到終止的'\\0'
。 復制到后server
,在字符server
中的字符后,立即按照MAC
而不終止'\\0'
之間。
你至少需要
struct client_config{
char name[20]; //en teoria son 6 + '\0'
char MAC[13]; // 12 characters + '\0'
char server[20];
int UDPport;
};
您還應該檢查strcpy
復制的內存不超過結構字段的可用內存。 也許使用strncpy
而不是strcpy
,但請確保結果以'\\0'
終止。 (閱讀strncpy
的文檔。)
問題是 MAC 字段沒有空間容納尾隨的\\0
字符。 C 中的所有字符串都需要比實際數據長一個字符。
為了使閱讀更安全,我建議對 fscanf 使用最大長度。 像這樣:
fscanf(conf, "%12s", word);
或者甚至更好,使用fgets
。 它可以很容易地使用最大長度的變量或常量。
fgets(word, MAXLENGTH, conf);
看起來您的 MAC 字段正好有 12 個字符,而尾隨 0 字符沒有位置,因此在打印過程中直接附加了以下服務器。
檢查struct client_config成員大小,不要忘記考慮字符串空終止符“\\0”。
不要忘記之前用零初始化struct client_config 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.