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;
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.
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.
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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With