[英]Invalid read of size 1 Valgrind
所以我在使用 Valgrind 時得到了這個錯誤:大小 1 的無效讀取。這是出現錯誤的程序部分。 至於程序是做什么的。 msgArr 是一堆存儲為字符串的整數。 然后我從 **msgArr 中提取 int 值並將其用作索引以從 **wordArr 中獲取字符。 我得到的字符,我存儲它們 ** 解碼。 然后我使用了一個 void 函數來打印出 **decoded 的內容,它可以正確打印出來,但我仍然沒有弄清楚為什么會發生這個錯誤。 你可以解釋嗎? 還有什么是 (vg_replace_malloc.c:762)? 編輯:第 285 行:main() 調用 decodeMsg(),第 242 行:decodeMsg() 調用 decodeWords()。
==31064== Invalid read of size 1
==31064== at 0x4E84029: vfprintf (vfprintf.c:1635)
==31064== by 0x4E8A458: printf (printf.c:34)
==31064== by 0x401488: printDecodedMsg (Project2_lhuynh22_204.c:181)
==31064== by 0x401679: decodeWords (Project2_lhuynh22_204.c:219)
==31064== by 0x4017BC: decodeMsg (Project2_lhuynh22_204.c:242)
==31064== by 0x401A26: main (Project2_lhuynh22_204.c:285)
==31064== Address 0x590349f is 0 bytes after a block of size 15 alloc'd
==31064== at 0x4C2BFB9: calloc (vg_replace_malloc.c:762)
==31064== by 0x40153E: decodeWords (Project2_lhuynh22_204.c:195)
==31064== by 0x4017BC: decodeMsg (Project2_lhuynh22_204.c:242)
==31064== by 0x401A26: main (Project2_lhuynh22_204.c:285)
==31064==
以下是出現錯誤的部分:
175 void printDecodedMsg(char **decoded, int wc){
176 int i;
177 for(i = 0; i < wc; i++)
178 | printf("%s ", decoded[i]);
179
180 printf("\n\n");
181 }
182
183 void decodeWords(char **msgArr, int wc, char **wordArr, int cpWc){
184 char *str, *token, *search = ",", **decoded;
185 int i,j, row, col, charCount;
186
187 decoded = calloc(wc, sizeof(char*));
188
189 for(i = 0; i < wc; i++){
190 | str = calloc(5000,sizeof(char));
191 | strcpy(str, msgArr[i]);
192 | decoded[i] = calloc(CHARMAX, sizeof(char));
193 | token = strtok(str, search);
194 | charCount = j = 0;
195 | while(token != NULL){
196 | | if(charCount % 2 != 0){
197 | | | col = atoi(token);
198 | | | if(col >= CHARMAX){
199 | | | | printf("%s!!!The word does not have that many characters!!!", SPACES);
200 | | | | exit(-1);
201 | | | }
202 | | | decoded[i][j++] = wordArr[row][col];
203 | | }
204 | | else{
205 | | | row = atoi(token);
206 | | | if(row >= cpWc){
207 | | | | printf("%s!!!The cipher text does not have that many words!!!", SPACES);
208 | | | | exit(-1);
209 | | | }
210 | | }
211 | | token = strtok(NULL, search);
212 | | charCount++;
213 | }
214 | free(str);
215 }
216 printDecodedMsg(decoded, wc);
217 freeMemChar(decoded, wc);
218 }
printf("%s", 解碼[i]);
這是行,我們正在讀取decode[i]
數組(接近第 181 行)
解碼[i] = calloc(CHARMAX, sizeof(char));
這是一行,我們將內存分配給decode[i]
數組(接近第 195 行)。 Valgrind 說,已經分配了 15 個字節。
decode[i]
字符數組分配足夠的內存來存儲\\0
(Null) 。 有關更多信息,請查看此鏈接: https : //www.cs.swarthmore.edu/~newhall/unixhelp/valgrind.phpPS:CHARMAX 的值無法提供精確解。 並且 valgrind 提供的行號可能與編輯器(IDE)的行號不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.