0

I recently wrote a program that is supposed to prompt a user for two strings, compare those two strings, and then display to the user whether they are the same or different. My program compiles okay but when I run it, after it prompts me for the strings, it comes up with "segmentation fault: 11". I'm not sure what I am doing wrong or how to fix it in this case.

// Compares two strings

#include <stdio.h>
#include <string.h>

int main(void) {
    char *s;
    char *t;
    int ret;

    // prompt user for two strings
    printf("string a: ");
    scanf("%s", s);
    printf("string b: ");
    scanf("%s", t);

    // compare strings
    ret = strcmp(s, t);
    if(ret == 0) {
        printf("Same\n");
    }
    else {
        printf("Different\n");
    }

    return 0;
}
  • You are dealing with pointers `s, t` that use random memory locations, i.e. you did not call `malloc()`. Take a look of some tutorial like this one: https://www.cprogramming.com/tutorial/c/lesson9.html. – karastojko Feb 13 '18 at 14:53
  • C does not have a string type like other "higher level" languages. Strings in C are arrays of characters, and everything about them, including memory allocation, has to be carried out manually. This is very much a FAQ, see the linked duplicate. – Lundin Feb 13 '18 at 14:55
  • @MathieudeLorimier whatever they are, they should have, well, actual storage space, arrays/malocs/whatever, not uninitialized values:( – Martin James Feb 13 '18 at 14:56
  • oh okay. I was confused because I have used this same method before in smaller programs that only prompted the user for one string and they worked fine. what's the reasoning as to why I would have to call malloc() in this case and not the others? – Jordan Owens Feb 13 '18 at 14:59
  • Probably you were lucky they did not crash. You have to use `malloc` always. – karastojko Feb 13 '18 at 15:02
  • oh okay. and i also have to define a length value for my *s, *t variables? – Jordan Owens Feb 13 '18 at 15:06
  • 1
    Either lengths if defined as arrays or sizes if defined over `malloc`. The tutorial explains it well and briefly. – karastojko Feb 13 '18 at 15:11

0 Answers0