c - getenv C 上的段错误?

标签 c segmentation-fault environment-variables getenv

因此,在编码时对我有帮助的是将我学到的所有内容协作到一个随机项目中。为了在编码时更好地帮助我和理解。我不久前了解了 getenv 并正在测试它。工作得很好,直到我回去学习 c 并再次打开项目......

#include <stdio.h>
#include <strings.h>
#include <windows.h>
#include <stdlib.h>

struct envvariabl3s
{
    char *userprofile;
    char *systemroot;

};

void loginscreen(void)
{
    int testbit = 4000000000;
    struct envvariabl3s *envariable;
    char *memtes;
    printf("\nWelcome to the login screen...\n");
    memtes = malloc(20 * sizeof(char));
    if(memtes == 0)
    {
        printf("Error: Not enough memory!");
    }
    strcpy(memtes, "Herp De Derp");

    printf("\nDynamically allocated memory is %s", memtes);
    free(memtes);

    envariable->userprofile = getenv("USERPROFILE"); //SEGFAULT HERE
    envariable->systemroot = getenv("SystemRoot");

    printf("\nUserProfile is: %s", envariable->userprofile);
    printf("\nSystem Root is: %s", envariable->systemroot);
    printf("%d", sizeof(testbit));
}

最佳答案

Envvariable 是一个指向结构的指针,但您从未创建一个结构来让它指向。它只是指向随机内存,并且分配给不存在的结构会导致崩溃。您需要一个实际的结构(可能是使用 malloc() 分配的)作为指向的指针。

关于c - getenv C 上的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029845/

相关文章:

c - 如何计算链表中的节点数?为什么输出显示节点数为 '2' ?

代码块调试器因程序参数而失败

c - 使用来自 char 的良好数据时出现段错误

当数据复制/扫描/读取到未初始化的指针时崩溃或 "segmentation fault"

reactjs - 使用 react 和 typescript 从 docker 容器获取环境变量

c - printf 精度控制问题

c - xcode 恢复以前的版本?

ios - 错误 "Constant ' self.apiKey' used before being initialized"in Initializer

c++ - 为 vector<string> 预留更大容量后发生段错误

javascript - Process.env 没有读取?亚马逊 S3 存储桶