Segmentation fault (core dumped) in a C program [duplicate] - c

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Segmentation fault (core dumped) in a simple C code
(3 answers)
Closed 8 years ago.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *Change(char *str,int start,int end)
{
if(start==end || start>end){
return str;
}
else{
char temp=str[start];
str[start]=str[end];
str[end]=temp;
return(Change(str,start++,end--));
}
return str;
}
char *Reverse(char *str)
{
int length=strlen(str);
return(Change(str,0,length-1));
}
int main()
{
printf("%s\n",Reverse("program"));
return 0;
}
I am trying to write a recursive function to reverse a string,but it comes the linking error.Please help.I had tried so many times and searched in the Internet,but it can't help.
I guess the most probably place causing the problem is in function Change,but I can't solve with it.

You're passing a string literal (which is a const char*) to Reverse(), since you can't modify a string literal, your program generates a segmentation fault.
You'll either need to pass a modifiable string to Reverse():
char myStr[] = "program";
printf("%s\n",Reverse(myStr));
Or you can make a copy of the input string in Reverse():
char *Reverse(const char *str)
{
int length=strlen(str);
char* temp = malloc(length);
strcpy(temp, str);
return(Change(temp,0,length-1));
}
In that case, you'll need to free the string returned by Reverse():
char* reverseStr = Reverse("program");
printf("%s\n", reverseStr );
free(reverseStr);
Also in change(), start++ end end-- will return the value before they are incremented, you need to use either ++start or simply start+1 since you won't use those variables anymore:
return(Change(str,start+1,end-1));

Simple explanation: You can't modify a string literal. One more thing is that the statement
return(Change(temp,0,length-1));
will cause compilation error because neither temp is defined in the function Reverse nor it is globally defined.

Related

How do I solve the error "Segmentation fault (core dumped)" [duplicate]

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Closed 3 years ago.
#include <stdio.h>
#include <string.h>
void space_to_tab(char *string) {
char str [strlen(string)];
int size = 0;
while(string[size] != '\0'){
if(string[size] == ' ')
str[size] = '\t';
else
str[size] = string[size];
size++;
}
*string = *str;
}
int main() {
char *str = "aa b";
printf("%s\n", str);
space_to_tab(str);
printf("%s\n", str);
}
I just started with C programming and I want to switch the spaces in a string with tabs and I get the error "Segmentation fault (core dumped)".
I belive the error is in "*string = *str;" but I dont know how to change the pointer of one string to the other.
You should not modify literal strings (i.e. "aa b") as this results in undefined behaviour (hence the segmentation fault). Instead you should modify an array like such:
char str[] = "aa b";
See In C, can I initialize a string in a pointer declaration the same way I can initialize a string in a char array declaration?

Copy string in C, using pointer [duplicate]

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Closed 4 years ago.
I am a beginner programmer. I wrote the following code to copy the one string into other, using pointers.
But I am not getting the output. The compiler says segmentation fault.
I have gone over and over the program, but to no avail. I am not able to locate the fault, and how to fix it.
It would be hard to believe but I have been stuck for almost 2 hours now.
Any help is greatly appreciated.
#include<stdio.h>
char *copy(char*, char*);
int main() {
char *str1 = "avanti";
char *str2 = "ujj";
printf("%s\n", str1);
char *result = copy(str1, str2);
printf("%s", result);
}
char *copy(char *str1, char *str2){
int i=0;
while (*(str2+i) != '\0') {
*(str1+i) = *(str2+i);
i++;
}
*(str1+i) = '\0';
return str1;
}
"avanti" is a string constant, not a place you can copy to. You might change it to char str1[] = "avanti"; This is an array of characters that is initialized with the value of the string constant "avanti"

Character type pointer memory allocation? [duplicate]

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Why is this string reversal C code causing a segmentation fault? [duplicate]
(8 answers)
Closed 5 years ago.
#include<stdio.h>
#define ASIZE 50
void Reverse(char *str){
int Asize,i=0;
char temp;
// Find the length of the string
while(*(str+i)!='\0'){
i++;
}
Asize=i;
// string reverse
for(i=0;i<(Asize/2);i++){
temp = *(str+i);
//may be below is some error with first input method 1
//but for input method 2 it works perfectly
*(str+i) = *(str+(Asize-(i+1)));
*(str+(Asize-(i+1))) = temp;
}
}
int main()
{
//input method 1. (error aries while i pass the pointer as argument)
char *s = "abcxyz";
//input method 2 (works perfectly while as function parameter)
char s[ASIZE];
scanf("%s",s);
Reverse(s);
printf("%s",s);
}
In the main the input method 1 not working perfectly for the reverse of the string, but the method 2 works.
The concept of mine is not clear with the memory representation of char pointer. Maybe I am not good to make the question correctly but Would someone please make me clear why the method 1 is not working. Thanks in advance for the help.
"abcxyz" is actually a const char[7] type that can decay to a const char* in certain situations.
It is not a char* type; the behaviour on attempting to modify the string is undefined.
char s[ASIZE]; on the other hand is an array of char with automatic storage duration. You are free to modify any element of that as you please.

replacing character in a pointer to char array [duplicate]

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Closed 7 years ago.
Okay so I just want to know why my program keeps crashing, all im trying to do is loop through the pointer to a char array and replace the old character with the new one and return how many times I have replaced it:
int main(void) {
char *s = "hello";
printf("%lu\n",str_replace_all(s,'e','f'));
printf("%s",s);
return 0;
}
size_t str_replace_all(char *s,int oldc,int newc) {
size_t count = 0;
for(;*s != '\0'; s++) {
if(*s == oldc) {
*s = newc;
count++
}
}
return count;
}
This compiles fine with gcc -ansi -W -Wall -pedantic but when i run it it crashes with this:
Segmentation fault (core dumped)
I need help figuring out whats going on, Thanks!
P.S expected output was hfllo
You're trying to modify a literal string, which produces undefined behavior. Change the declaration to:
char s[] = "hello";
The reason why you are getting a segmentation fault is that there is no memory allocated for the variable s. It is just a pointer pointing to some address location. Possible solution is char s[] = "hello" or you can allocate some memory in heap and memcpy or strcpy "hello" to the char pointer. Then you code will work. Hope it clears the concept. :)

Segmentation fault (core dumped) in C, The C Programming Language by K&R Exercise 2.5 [duplicate]

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Closed 9 years ago.
I am writing a code for squeeze(s1,s2) that deletes each character in string s1 that matches any character in string s2 and I get "Segmentation fault (core dumped)" when I try to run the program.
I believe the error comes from in how i call the function inside the main(). I am a beginner and I don't know how to call functions. Please help!
#include<stdio.h>
void squeezer(char s[], char c[]);
main()
{
squeezer("abcdefgabcdefgabcdefg", "abcd");
}
void squeezer(char s[], char c[])
{
int i,j,k,z;
for(k=0; c[k] != '\0'; k++) {
for(i=j=0;s[i] != '\0';i++) {
if (s[i] != c[k]) {
s[j++] = s[i];
}
s[j] = '\0';
}
}
for(z=0; z < j; z++)
printf("%c",s[z]);
}
You are passing string literal to your function and then trying to modify it. You can't modify a string literal. Modifying a string literal invokes undefined behavior. In such case you may get either expected or unexpected result You may get segmentation fault or program crash too.
You can change your main function as
int main(void)
{
char s1[] = "abcdefgabcdefgabcdefg";
char s2[] = "abcd";
squeezer(s1, s2);
}
Must read: comp.lang.c FAQ list ยท Question 1.32.
String literals are "constant", read-only. You cannot change them, and that is what squeezer() tries to do.
You're writing to string literals, which is undefined behaviour. If your compiler put them in read-only memory, then your program should segfault. Try making writable copies of your strings in main, like so:
int main(int argc, char** argv)
{
char s[] = "abcdefgabcdefgabcdefg";
char c[] = "abcd";
squeezer(s, c);
return 0;
}
Depending on the C compiler and operating system you are using, the string literal you pass to squeezer may be "read-only" -- i.e. immutable -- at run-time. This is the same mechanism meant to prevent modification of compiled code at run-time.
The fix is to allocte a character array large enough to hold s using malloc or declare a char s[80] in main or as a global variable and then use strcpy to copy your first string literal into s before passing it as the first argument to squeezer.
Alternatively, you could pass the allocated or declared array variable as a third argument to squeezer and copy the "squeezed" string into it. Or, if you want to make squeezer as robust as you can, allocate a result array with malloc in squeezer that is strlen(s) in size, use it to accumulate the "squeezed" letters, and then return the pointer to the allocted array from squeezer whose return type will have changed from void to char *.

Resources