8

this is my code giving segmentation fault

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(void) {
    char *get;
    scanf("%s", get);
    int k = strcmp("sachin", get);
    printf("%d", k);
}

thanks for any help;

stefan
  • 10,215
  • 4
  • 49
  • 90
Sachin Setiya
  • 273
  • 1
  • 3
  • 13

3 Answers3

4
char *get;

The above statement defines get to be a pointer to a character. It can store the address of an object of type char, not a character itself. The problem is with both scanf and strcmp call. You need to define an array of characters to store the input string.

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

int main(void) {
    // assuming max string length 40
    // +1 for the terminating null byte added by scanf

    char get[40+1];

    // "%40s" means write at most 40 characters
    // into the buffer get and then add the null byte
    // at the end. This is to guard against buffer overrun by
    // scanf in case the input string is too large for get to store

    scanf("%40s", get);
    int k = strcmp("sachin", get);
    printf("%d", k);

    return 0;
}
ajay
  • 9,402
  • 8
  • 44
  • 71
2

You need to allocate memory for the pointer get.

Or use a char array:

char   get[MAX_SIZE];
scanf("%s",get);

When you declare a pointer, it is not pointing to any memory address. You have to explicitly allocate memory for that pointer by malloc (c-style) or new (c++ style).

You will also need to manage the clean operation yourself by free / delete respectively.

Abhishek Bansal
  • 12,589
  • 4
  • 31
  • 46
0

of sure you get a segment fault. you told your computer to write user input to uninitialized pointer.

char   *get; // just a pointer that may wildly points anywhere
scanf("%s",get);

define get to be some char array

char get[SOME_LARGE_CONSTANTS_THAT_CLEARLY_IS_LARGER_THAN_YOUR_USER_INPUT];
vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80