This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 4 years ago.
Here is a simple program that is a function which checks for the character 'a' within a string, then returns the character if found, and NULL if it is not found. I am not really sure if it is the function or the call of the function itself, here is the code.
#include <stdio.h>
char *find_char(char *str, char character);
int main(){
char *str;
printf("str\n");
scanf("%s", str);
printf("%c",*find_char(str,'a'));
return 0;
}
char *find_char(char *str, char character){
char *pstr = str;
while(*pstr!='\0' && *pstr!=character){
pstr++;}
if (*pstr!=character)
return NULL;
else
return pstr;
}
Your problem basically lies in these two lines, the first and third code line of your main function:
char *str; // Create pointer, pointing to ***arbitrary*** memory.
scanf("%s", str); // Write to that memory, undefined behaviour.
You need to create backing storage for the pointer so you have somewhere valid to write your input to.
A better idea would be to use a rock-solid input routine rather than relying on often-dodgy practices like writing to invalid memory, or allowing uncontrolled input into limited-size buffers. One such beast can be found here.
Related
This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 5 months ago.
#include <stdio.h>
void swapchars(int Q,char* L){
char *ptr;
for(int i=0;i<Q-1;i+=2){
*ptr= *(L+i);
*(L+i)= *(L+i+1);
*(L+i+1)= *ptr;
}
}
int main() {
// Write C code here
int N;
scanf("%d",&N);
char str[N+1];
scanf("%s",str);
swapchars(N,str);
printf("%s",str);
return 0;
}
I don’t know what is wrong with this code it keeps generating segfault although when I used the same loop directly in the main function without an external function the code was working properly
You haven't initialized ptr to anything, so dereferencing it is undefined - you are writing to a random place in memory.
Think about whether you really need a pointer to store the intermediate value.
This question already has answers here:
Returning an array using C
(8 answers)
Closed 2 years ago.
I have a code and can't figure out why it's crashing (segmentation fault) I know from past posts that it has something to do with unaccessable memory (I think), but I initialized my "input" variable.
#include <stdio.h>
#include <stdlib.h>
char *getInfo() {
char input[1000];
scanf("%s", input);
return input;
}
int main() {
char *x;
x = getInfo();
printf("%s\n", x);
return 0;
}
When I run and backtrace the program inside gdb, it says (among other things) "... in main () at error.c:11"
When I break at line 11 after giving input ("bark") try to print the variables, print input gives me '\000 x29' and print x gives me 0x0. I know that 0x0 means that it's null, and I think \000 also means null, but I don't get why., when I scaf'ed input, shouldn't the null be replaced?
Your function getInfo returns the address of the local variable input. But this variable is deleted when the function returns, so the pointer is becoming invalid. The regular way to solve this is by passing the array into the function as a parameter.
char *getInfo(char *input) {
scanf("%s", input);
return input;
}
and on the caller side:
char input[1000];
char *x = getInfo(input);
Of course in your case I would just move the call to scanf into main:
char input[1000];
scanf("%s", input);
printf("%s\n", input);
Please also note that your call to scanf is not safe as scanf might read more input than the buffer can hold. Also my very simple change for getInfo has the disadvantage that you do not pass the length. Normally you should pass the pointer to the buffer and the size of the buffer. That way you can make sure that the function does not overflow the buffer.
For safer variants in your case you might also consider one of these lines:
scanf("%999s", input);
fgets(input, 1000, stdin);
This question already has answers here:
SIGSEV on strcmp of memset string
(3 answers)
Closed 3 years ago.
Why do i get a crash on strcpy even. I tried appending a 0,\0,\n using sprintf and check in gdb that its appended correctly but still i get a crash.
With malloc i dont get a crash, but somebody told me that malloc is not necessary in this case.
include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_LINE_SIZE 10
int main()
{
char* str[100];
int strCount=0;
char cCmd[] = "<some command>|awk '{print $1}'";
FILE *fp;
fp = popen(cCmd,"r");
if(cCmd != NULL)
{
char line[MAX_LINE_SIZE];
while (fgets(line, sizeof(line), fp) != NULL )
{
//str[strCount]=malloc(MAX_LINE_SIZE);
//sprintf(line,"%s%c",line,'\0'); -- even with appending a null character at the end it doesnt work
strcpy(str[strCount],line);
//strip(str[strCount]);
(strCount)++;
}
}
return 0;
}
The problem is in this statement strcpy(str[strCount],line)
char *str[100]; declares an array of 100 uninitialized pointers whereby each pointer needs to be allocated memory explicitly.
When you run str[strCount]=malloc(MAX_LINE_SIZE); statement, you are actually allocating memory for invidual pointers which is further used by strcpy to copy string.
When you are not using malloc, its an uninitialized pointer (having no allocated memory) causing strcpy to fail as you are coping in memory that may not belong to you or may not exist at all.
This question already has answers here:
Access violation when using strcpy?
(8 answers)
Closed 9 years ago.
#include <stdio.h>
char *strcpy_r(char* s, char* t);
int main()
{
char *s = {"Bob"};
char *t = {"Billy"};
char *ptr;
ptr = strcpy_r(s, t);
printf("%s\n", ptr);
return 0;
}
char* strcpy_r(char* s, char* t)
{
if((*s = *t) != '\0')
strcpy_r(s + 1, t + 1);
return s;
}
I'm just doing this for practice, but when I compiled it. I got a seg fault from main. Could someone tell me what might've caused this seg fault?
Congratulations, you have invoked undefined behavior twice within one line.
First, you can't modify the contents of a string literal. So strcpy()ing onto "foo" is wrong.
Two, even if you could: you're copying a string to a buffer that is shorter than the string. This is UB again.
You are trying to modify a constant string. This is wrong! Chances of segfault live when you modify a constant string.
Instead do this:
char s[10] = "Bob";
char t[10] = "Billy";
char *ptr;
You can't overwrite the memory that's used to hold a quoted string. That'll segfault instantly.
String literals are constant, i.e. they cant change. You're also trying to copy a longer string into a shorter string, which will write beyond the bounds of the destination string.
Both of these problems leads to undefined behavior which can cause a crash.
To solve the first problem, you have to use an array for the destination string. To solve the other problem, you have to make sure the destination array is at least as large as the source string (including its terminating '\0').
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
Here is a small function, was testing something so wrote it. Here i tried to increment a character value of the string literal when i tried doing so i got a segmentation fault. Can you please tell what i am doing wrong here
#include <stdio.h>
int input_string(char *str)
{
printf("%s\n", str);
printf("%c\n", *str);
printf("%c\n", (*str)++); // I get a segmentation fault here, cant i increment the value like this ?
}
void main()
{
char *str = "andrew";
input_string(str);
}
What this char *str = "andrew"; does is create a pointer to a string that MAY be located on .text (where the executable code resides) and trying to modify it is undefined behavior.
Change it for this:
char str[] = "andrew";
It will make a copy of the string in a stack allocated buffer that you can safely modify.
This:
char *str = "andrew";
means what str points to a constant string literal. You will get undefined behavior if you try to change it.
If you want to perform string manipulation, define a character array.