1
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) 
{
    char key, vector;
    char plainText[101];
    char cipher;
    int i, cipherValue;
    int keyLength, IVLength;

    scanf("%s", key);
    scanf("%s", vector);

    return 0;
}

My program crashes after I input values for the scanf parts. I don't understand why.

sg7
  • 6,108
  • 2
  • 32
  • 40
ancd3ea4
  • 195
  • 1
  • 1
  • 14
  • 2
    Compiler warnings: enable them (here, `-Wformat` for `gcc` or `clang`) and heed them. – Davis Herring Feb 02 '18 at 03:24
  • 3
    Possible duplicate of [Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer](https://stackoverflow.com/questions/37549594/crash-or-segmentation-fault-when-data-is-copied-scanned-read-to-an-uninitializ) - it's not an exact duplicate, but the reason is similar and reading the solution should be enough. – viraptor Feb 02 '18 at 03:25
  • 1
    @viraptor: These aren’t even pointers! – Davis Herring Feb 02 '18 at 03:26
  • @DavisHerring I understand - and that's why I'm saying it's not an exact duplicate. The answers there are better than anything we could write here though. (unless you want to explain pointer / value difference from scratch :) ) – viraptor Feb 02 '18 at 03:28
  • I'm not sure I understand what you mean for me to do @DavisHerring – ancd3ea4 Feb 02 '18 at 03:29
  • @Occazn: The compiler can help you find (many of) these basic mistakes without having to ask here. You do have to know how to turn the warnings on, though. – Davis Herring Feb 02 '18 at 05:48

1 Answers1

2

The problem with

scanf("%s", key);
scanf("%s", vector);

is:

  1. key and vector are of type char, not pointers to char. The can hold one character only.1
  2. With %s scanf expects a pointer to char. As it stands right now, you are passing uninitialized integer values as if it were pointers, that's undefined behaviour and your program crashes as a result of it. The compiler must have given you a warning about this, don't ignore the compiler's warnings, they are there to help you, not annoy you.

The correct version:

char key[101], vector[101];
...
scanf("%s", key);
scanf("%s", vector);

// or to limit the number of bytes
// written in the buffer, as pointed out
// in the comments by user viraptor
scanf("%100s", key);
scanf("%100s", vector);

For more information about scanf, please read the documentation


Footnote

1A string in C is a sequence of characters that ends with the '\0'-terminating byte. A string with one single character needs a char array of dimension 2 or more. In general, a char array of dimension n can store strings with maximal length of n-1. You have to keep that in mind when passing pointers to char to functions when they expect strings. A pointer to a single char will lead to undefined behaviour because it overflows.

Pablo
  • 13,271
  • 4
  • 39
  • 59