Valgrind 消息:条件跳转或移动取决于未解析的未初始化值

Valgrind message: Conditional jump or move depends on uninitialised value(s) unresolved

我正在尝试一个新的任务:我需要将环境变量从 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)

PrintString 中,您没有使用正确的循环控制:

for(int j = 0; strings[j] != NULL; j++)

你传递 int counter 告诉你有多少条目,但你没有使用它。您反而寻找 NULL 条目,但您从未设置 NULL 条目,也没有在数组中为其分配 space。

所以请改用 counter

for(int j = 0; j<counter; j++)