【问题标题】:Segmentation fault on getenv C?getenv C上的分段错误?
【发布时间】:2014-02-26 01:27:08
【问题描述】:

所以在编码时帮助我的是将我学到的所有东西整合到一个随机项目中。在编码时更好地帮助我和理解。我不久前了解了 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));
}

【问题讨论】:

    标签: c segmentation-fault environment-variables getenv


    【解决方案1】:

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

    【讨论】:

    • 是的,对不起,我是个白痴,我不小心删除了该结构,但没有意识到这一点。对不起!
    • 应该是 struct envvariabl3s *envariable, datvar;然后有 envariable = &datvar;
    • 考虑采用始终在 C/C++ 中显式初始化变量的做法。如果您在声明它们时初始化指向NULL 的指针,这将更容易被发现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 2016-06-08
    • 2015-01-26
    • 1970-01-01
    相关资源
    最近更新 更多