0

This code doesn't work and I don't know why, I used everything exactly as my professor told us and I think it should work, why does compiler throw Segmentation fault(core dumped) exception. What am I doing wrong?

int main() {
    int n;
    char *chr;
    char pchr;
    scanf("%s", chr);
    scanf(" %d", &n);

    char **table = (char **) malloc(n * sizeof(char*));
    char *chr2 = chr;
}

this is only part of my program but when I run only this code compiler throws an exception. It doesn't even scan an n number it only scans char and then throws an exception. Thank you for answers.

Nik
  • 1,780
  • 1
  • 14
  • 23
Nejc Ahtik
  • 43
  • 5
  • The pointer chr has inderterminate value. As result the program has undefined behavior due to the statement scanf("%s", chr);. – Vlad from Moscow Apr 01 '18 at 17:16
  • If you enable warnings your compiler should tell you something along the lines of "Using uninitialized variable chr". – a3f Apr 01 '18 at 17:16
  • Scant reads stdin and stores what matches the pattern(format) in the memory which chr points at. Which is undef. – Mischa Apr 01 '18 at 17:18

1 Answers1

0

As you obviously noticed, the issues are here:

char *chr;
scanf("%s", chr);

What scanf does is place the string it reads from console input into some memory address pointed to by chr. As some have already mentioned, your problem here is two-fold

  1. chr is not initialized, thus giving you undefined behaviour as that variable has an indeterminate value. See this answer for info on why this is.
  2. chr has to point to some allocated memory. This can be done in a couple ways, 1) By using a char[] or allocating memory with malloc and friends.

So there are two way you can go about it:

#define BUFFERSIZE 50
char chr[BUFFERSIZE] = {'\0'};
scanf("%s", chr);

OR

char* chr = calloc(BUFFERSIZE, sizeof(char));
scanf("%s", chr);
free(chr);
chr = NULL;

Next, this line doesn't do what you think it does:

char **table = (char **) malloc(n * sizeof(char*));

Please see this answer to see how you would approach allocating a pointer list.

Nik
  • 1,780
  • 1
  • 14
  • 23