0

The following code compiles but I get an access violation at runtime.

typedef struct login
{
    char *name;
    char *pw;
}login;

 int _tmain(int argc, _TCHAR* argv[])
{
    login user1, user2;
    GetUser(user1);

    printf("\nUN is %s, PW is %s", user1.name, user1.pw);

    GetUser(user2);

    printf("\nUN is %s, PW is %s", user2.name, user2.pw);

    getch();
    return 0;
}

void GetUser(login &user)
{
    char *name;
    name = (char*)malloc(20);
    printf("Enter User Name: ");
    fflush(stdin);
    scanf("%s", name);
    user.name = name;

    printf("Enter password: ");
    user.pw = GetPassword();
    free(name);
}

If I change the char *name; to a char[20]; in the struct, the code works fine.

I modified the above code using malloc but after the second call to GetUser(user2); user1.name == user2.name. user1.pw and user2.pw are as expected

2
  • 2
    You are using reference type in the code. But the question has c tag Commented Apr 30, 2017 at 23:27
  • void GetUser(login &user) is not valid C. Commented May 1, 2017 at 1:14

1 Answer 1

2

char* does not point to anything. You need to malloc enough bytes to hold the input you are reading.

Sign up to request clarification or add additional context in comments.

1 Comment

would it be better practice to change the struct to char name[20]; or to change the GetUser(...) function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.