0

I've been trying to figure out this segmentation fault for hours. Every time I use the char* find I get a seg fault.

char* find = malloc(sizeof(char) * 20);

displayMatrix(rowcol, matrix);
// (Don't mind that ^^^)

printf("Enter a word to find in the puzzle : \n");
scanf("%s", &find);
tolower(find);
len = strlen(find) + 1;

When I run the program, it seg faults right as it gets to

len = strlen(find) + 1

Anyone know why it's doing this? Thanks in advance.

Naman
  • 27,789
  • 26
  • 218
  • 353
Yogurt4655
  • 13
  • 2
  • 2
    Because you meant to use `scanf("%s", find);` probably. – user253751 Dec 02 '15 at 02:19
  • 3
    `tolower()` Does not work like that. Either you disabled compiler warnings or, you ignore them. And there is no way that `sizeof(char) != 1` so don't use that. – Iharob Al Asimi Dec 02 '15 at 02:20
  • Oh geez. I haven't been using -Wall this whole time. Thanks for pointing that out. – Yogurt4655 Dec 02 '15 at 02:24
  • Put a debug print between `scanf`, `tolower` and `len` of `printf("Here!\n");` and then see where the code is actually failing. – dave Dec 02 '15 at 02:26

2 Answers2

0

scanf("%s", &find); should be scanf("%s", find); find is already the address of the string.

and tolower is incorrect, too: int tolower ( int c ); not int tolower ( char *c );

artm
  • 17,291
  • 6
  • 38
  • 54
0

Other way to do it would be point to a string literal using const char * and changing the rest of the code as:

const char* find = (char*) malloc(sizeof(char)*20);
printf("Enter a word to find in the puzzle : \n");
scanf("%s", find);
printf("find says : I have got this saved under me %s \n", find); //just tried checking if it works
tolower(find); //this surely needs some correction,determine what you want
int len = strlen(find); //you won't require +1 using strlen
printf("%d : It Works Fine.",len);
Naman
  • 27,789
  • 26
  • 218
  • 353
  • Where do you find the need to cast the result of *malloc*? – Déjà vu Dec 02 '15 at 03:03
  • @ringø referring to `void *malloc(size_t);` shouldn't I be doing that? – Naman Dec 02 '15 at 03:09
  • Well, google it. [this](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) for intance. – Déjà vu Dec 02 '15 at 03:10
  • @ringø : thanx for that, leads to why for `char* find = malloc(sizeof(char)*20);` would CLion display `Incompatible pointer types 'char*' and 'void*'` ...shouldn't it be following such practice? – Naman Dec 02 '15 at 03:18