Copy string in C, using pointer [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)
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"

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?

Reversing a string literal in C with pointers [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 5 years ago.
I am trying to reverse a string literal with the use of pointers, though my code received SEGSIGV signal on *head=*tail line
char* reverse(char* input, int n) {
char temp;
char* head= input;
char* tail= &input[n-1];
while(head<tail){
temp=*head;
*head=*tail;
*tail=temp;
head++;
tail--;
}
return input;
}
int main(void){
char* sentence= "All work and no play makes jack a dull boy";
reverse(sentence, strlen(sentence));
printf("%s", sentence);
return 0;
}
I don't know if I am trying to access restricted memory segment.
Yes, you are trying to modify read-only memory.
You cannot rearrange a constant string.
With a simple change you can fix it:
char sentence[] = "All work and no play makes jack a dull boy";
(use an array instead of a pointer)

sprintf crashes but it is unclear why [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 6 years ago.
I tried the following code with sprintf, but it crashes in some cases and works fine in the other. Could anyone explain it to me?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//char *s = malloc(20); //works fine
//char *s = ""; //does not work, no matter what the initial value is
char s[20]; //works fine
sprintf(s, "%s", "hello world");
printf("%s",s);
return 0;
}
When you are doing this:
char *s = "";
or
char *s = "longer string";
You are creating a literal string which is possibly placed in read-only memory. So you cannot change it later.
If you try to do the following syntax:
char s[] = "...";
the array will be initialized with the literal string and you will be able to modify the original array later.
Suggested questions on site:
What is the difference between char s[] and char *s in C?
Why do I get a segmentation fault when writing to a string initialized with “char *s” but not “char s[]”?

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 a C program [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)
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.

Resources