-2

So what helps me when coding is collaberating everything i've learned into one random project. To better help me and understand when coding. I learnt about getenv a while back and was testing it. Worked fine until I went back to work on learning c and opened the project again...

#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));
}
John
  • 73
  • 2
  • 8

1 Answers1

1

Envvariable is a pointer to a structure, but you never created a struct for it to point to. It just points to random memory, and assigning into the struct that isn't there causes the crash. You need an actual struct, perhaps allocated using malloc(), for the pointer to point to.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • Yeah sorry im an idiot o-e I accidentally deleted the struct and didn't realize it. Sorry! – John Feb 26 '14 at 01:36
  • It should've been struct envvariabl3s *envariable, datvar; then had envariable = &datvar; – John Feb 26 '14 at 01:39
  • Consider adopting the practice of always explicitly initializing your variables in C/C++. This would've more easily been caught if you initialized your pointers to `NULL` at the point they're declared. – jia103 Feb 26 '14 at 02:15