我正在嘗試一個新的任務:我需要將環境變數從 shell 復制到一個陣列中,然后將它們小寫并列印回來。(我使用 Ubuntu 20.04.4 LTS、gcc 來編譯和用 C 語言撰寫我的代碼)。有人建議我使用 malloc 創建陣列,但決定不這樣做。一切都很順利,直到我試圖,出于我自己的原因,看看我創造了什么。然后,當通過 valgrind 運行它時 - 我收到了這個錯誤,我不太確定為什么以及如何修復。我會很感激幫助。
至于代碼:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
char PrintString(char **strings, int counter)
{
for(int j = 0; strings[j] != NULL; j )
{
printf("%s \n", strings[j]);
}
return (4);
}
/*----------------------------------------------*/
//function to lowercase the strings
char Lowercase(char **array, int seq_num) //seq_num is the size of the array
{
int i;
int j;
for (i = 0; i < seq_num; i ) //for every line in the env list
{
for(j = 0; j < strlen(array[i]); j ) //for every character in the env strings
{
array[i][j] = tolower(array[i][j]);
}
printf("%s\n", (array[i]));
}
return(**array);
}
/*----------------------------------------------*/
//in order to get the number of the env var - this is the block
int Conut_variables(char **envp)
{
int counter=0; //counter for the no. of variables
for(int i = 0; envp[i] != NULL ; i )
{
counter ;
}
return(counter);
}
/*----------------------------------------------*/
int main(int argc, char *argv[], char *envp[])
{
int counter = Conut_variables(envp);
int i,j;
char *new_buffer[counter];
for(i = 0; envp[i] != NULL; i )
{
new_buffer[i] = envp[i];
}
Lowercase(new_buffer, counter);
PrintString(new_buffer, counter);
return (0);
}
/*----------------------------------------------*/
至于錯誤:
==20052== Conditional jump or move depends on uninitialised value(s)
==20052== at 0x10922E: PrintString (Ex4vol2.c:9)
==20052== by 0x1094CB: main (Ex4vol2.c:53)
==20052== Uninitialised value was created by a stack allocation
==20052== at 0x109364: main (Ex4vol2.c:44)
==20052==
==20052==
==20052== HEAP SUMMARY:
==20052== in use at exit: 0 bytes in 0 blocks
==20052== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==20052==
==20052== All heap blocks were freed -- no leaks are possible
==20052==
==20052== For lists of detected and suppressed errors, rerun with: -s
==20052== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
uj5u.com熱心網友回復:
如果PrintString您沒有使用正確的回圈控制:
for(int j = 0; strings[j] != NULL; j )
你通過 intcounter告訴你有多少條目,但你不使用它。相反,您尋找一個NULL條目,但您從未設定NULL條目,也沒有在陣列中為其分配空間。
所以counter改用。
for(int j = 0; j<counter; j )
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/478899.html
上一篇:在GitLabCI/CD管道中使用Chrome驅動程式運行UI測驗
下一篇:資料包套接字沒有接收到資料
