0

I am trying to get input from the console with this code but it gives me runtime exception at some memory location each time I try to run it and enter the first possible input. I am using Visual Studio 2010. I got same problems with MingW and Dev C++. However, the code ran fine with the old TurboC3 compiler.

int Nowhere(int x);
...
char* AtBashEncrypt(char* message);
char* AtBashDecrypt(char* encrypted);

int main()
{
    char *input = "", *ciphertext = "", *plaintext = "";
    system("cls");
    printf("AtBash Cipher\nEnter a string to be encrypted: ");
    gets(input); //this is where I get the error
    ciphertext = AtBashEncrypt(input);
    ...
    getch();
}

What could possibly be wrong with it?

Nikhil Girraj
  • 1,135
  • 1
  • 15
  • 33

1 Answers1

1
 char *input = "";

is a pointer pointing to a string literal residing in read only memory you cannot modify its contents. Any attempt to do so results in undefined behavior. What you need is an array.

#define MAX_SIZE 256
char input[MAX_SIZE]="";

Good Read:
What is the difference between char a[] = ?string?; and char *p = ?string?;?

Also, you should use fgets instead of gets

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • And not only that, `gets()` is a broken function that should never ever be used (because it's almost impossible to avoid buffer overflows). – John Zwinck Mar 08 '13 at 03:58
  • @JacobAbrahams: The argument is not valid because *even if was writable* is a assumption that does not hold good in this case. – Alok Save Mar 08 '13 at 04:03
  • @JohnZwinck: True, indeed. – Alok Save Mar 08 '13 at 04:03
  • @NikhilGirraj: Because Undefined behavior does not necessarily mandate a segmentation fault, Undefined behavior means that the observed behavior simply cannot be defined, it can be anything from a crash to normal working of program to blowing up your computer(*theoretically*). On a side note, turbo compiler is quite old and bug prone and you should consider moving to a more stable and updated compiler like gcc or msvc or clang. – Alok Save Mar 08 '13 at 04:12
  • @AlokSave: That helps! I think I should start reading more about it, any suggestions will be again very helpful. – Nikhil Girraj Mar 08 '13 at 04:20