Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcmp giving segmentation fault [duplicate]

Tags:

c

pointers

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;

like image 463
Sachin Setiya Avatar asked Mar 20 '14 08:03

Sachin Setiya


People also ask

How do I find out what is causing my segmentation fault?

Use debuggers to diagnose segfaults Start your debugger with the command gdb core , and then use the backtrace command to see where the program was when it crashed. This simple trick will allow you to focus on that part of the code.

Why is Strcpy giving me a segmentation fault?

Solution 1. a segmentation fault occurs when the program tries to write to a part of memory that the kernel does not allow access to. Your 2 char* pointers are not initialized and so could point to anywhere. then when you try to write to these pointer you will get a segmentation fault.

Can out of memory cause segmentation fault?

Segmentation fault is an error caused by accessing invalid memory, e.g., accessing variable that has already been freed, writing to a read-only portion of memory, or accessing elements out of range of the array, etc.


2 Answers

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;
}
like image 174
ajay Avatar answered Nov 10 '22 12:11

ajay


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.

like image 29
Abhishek Bansal Avatar answered Nov 10 '22 13:11

Abhishek Bansal