0

I am writing simple program in visual studio c++ 2012. I take some input dynamically. While printing on console int values it works fine but printing char *somevariable it stops and give error program.exe has stopped working.

my program is like

#include <stdlib.h>
#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    int choice;
    //char *userName;
    static char* password;
    static char* firstname;
    static char* lastname;
    static char* username;
    char* name;

    printf("\n 1.Login");
    printf("\n 2.register");

    printf("\nEnter choice");
    scanf("%d", &choice);
    printf("\n%d", choice);

    switch (choice) {

    case 1:
        printf("\n Enter username :");
        scanf("%s", &username);
        printf("\n Enter username :");
        scanf("%s", &password);
        break;
    case 2:
        printf("\n Enter Firstname :");
        scanf("%s", &firstname);
        printf("\n Enter lastname :");
        scanf("%s", &lastname);
        printf("\n Enter username :");
        scanf("%s", &username);
        printf("\n Enter username :");
        scanf("%s", &password);
        printf("\n");
        //name = "sdfjsdjksdhfjjksdjfh";
        printf("%s", password);
        break;
    default:
        printf("\n Wrong Choice Entered..");
        break;
    }

    getchar();
    return 0;
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64
newbee
  • 89
  • 7

2 Answers2

0

I am assuming you are referring to the line

printf("%s",password);

This line should read

printf("%p", (void*) &password);

This is explained very well in the accepted answer to this question Correct format specifier to print pointer (address)?

Community
  • 1
  • 1
Chris
  • 57
  • 6
0

static char* password; declares a pointer to char. Just the pointer. It doesn't point that pointer anywhere and doesn't allocate any memory for it point at.

scanf("%s", &password);

reads console input and stores it in the memory starting at the address of password.

  • Q. What is at that address?

  • A. A pointer to char (password).

  • Q. How much memory does a pointer to char occupy?

  • A. 4 bytes or 8 bytes (depending on whether you're in a 32- or 64-bit system).

  • Q. How many bytes will you write starting at the address of password if you input "sdfjsdjksdhfjjksdjfh"?

  • A. 21.

So you're writing the extra 13 or 17 bytes of password into... what memory? We don't know, but we can dependably say that it is occupied by some of the code of your program, because overwriting your own program with garbage will cause it to stop working, sometime before its natural end.

Solution? Find a good book about programming in C and learn the basics. Failing that, at least read the documentation of scanf, including the example code.

Community
  • 1
  • 1
Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182