Replace individual character element of a string C [duplicate] - c

This question already has answers here:
How to replace specific characters in a string with other characters
(3 answers)
Closed 9 years ago.
I am trying to do something really basic on C but I keep getting a segmentation fault. All I want to do is replace a letter of a word with a different letter- in this example replace the l with a L. Can anyone help explain where I have gone wrong? It should be a really basic problem I think, I just have no idea why its not working.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
char *string1;
string1 = "hello";
printf("string1 %s\n", string1);
printf("string1[2] %c\n", string1[2]);
string1[2] = 'L';
printf("string1 %s\n", string1);
return 0;
}
For my output I get
string1 hello
string1[2] l
Segmentation fault
Thanks!

string1 = "hello";
string1[2] = 'L';
You can't change string literals, it's undefined behavior. Try this:
char string1[] = "hello";
Or maybe:
char *string1;
string1 = malloc(6); /* hello + 0-terminator */
strcpy(string1, "hello");
/* Stuff. */
free(string1);

char *string1;
string1 = "hello";
string1 points to a string literal and string literals are non-modifiable.
What you can do is initialize an array with the elements of a string literal.
char string1[] = "hello";
the elements of string1 array are modifiable.

char *string1 = "hello";
When running the code, the string literal will be in a section that is read-only. OS does not allow the code to change that block of memory, so you get a seg-fault.
char string1[] = "hello";
The string literal will be pushed onto the stack when you run the code.

string1[2] = 'L';
you are trying to change a string literal which is undefined behavior in C.
Instead use string1[]="hello";
Segmentation fault you get is because the literal is probably stored in the the read only section of the memory and trying to write to it produces undefined behavior.

Related

Weird segmentation fault (difference between arrays and pointers ?)

i cant see why i'm getting segmentation fault from this code and somehow when i use arrays instead of pointers it works, i would be happy if anyone can make me understand this.
void main() {
char *str = "example string";
wrapChrInStr(str, 'a');
}
void wrapChrInStr(char *str, unsigned char chr) {
char *ptr = str;
char c;
while((c = *ptr)) {
if(c != chr) {
*str = c;
str++;
ptr++;
} else {
ptr++;
}
}
*str = '\0';
}
Thank you. I'm doing a lot of c programming and its really weird that i never faced that before.
Probably because you don't realize that there are different ways of storing a
C-String. You may have been lucky enough never to have encountered a segfault
because of this.
String literals
A string literal is declared with double quotation marks, e.g.
"hello world"
This string is usually stored in a read-only section. When using string
literals, it's best to declare the variables with a const like this:
const char *str = "hello world";
With this you know that str is pointing to read-only memory location and you cannot
manipulate the contents of the string. In fact, if you do this:
const char *str = "hello world";
str[0] = 'H';
// or the equivalent
*str = 'H'
the compiler will return an error like this:
a.c:5:5: error: assignment of read-only location ‘*str’
which I found very helpful, because you cannot accidentally manipulate the
contents pointed to by str.
Arrays
If you need to manipulate the contents of a string, then you need to store the
string in an array, e.g.
char str[] = "hello word";
In this case the compiler knows that the string literal has 10 characters and reserves 11 bytes (1 byte for '\0' - the terminating byte) for str and initializes the array with
the contents of the string literal.
Here you can do stuff like
str[0] = 'H'
but you cannot access beyond the 11th byte.
You can also declare an array with a fixed size. In this case the size must be
at least the same as the length+1 of the string literal.
char str[11] = "Hello world";
If you declare less space (char str[3] = "hello world"; for example),
your compiler will warn you with something like this
a.c:4:14: warning: initializer-string for array of chars is too long
but I'm not sure what happens if you execute the code anyway. I think this is a case of undefined behaviour
and that means: anything can happen.
Personally, I usually declare my string without a fixed size, unless there is
a reason for having a fixed size.

Segmentation Error in C Code [duplicate]

This question already has answers here:
Why can't I use this code to overwrite a string?
(4 answers)
Closed 9 years ago.
I am totally new to C and I am about to write a function that reverses a string. My code looks like this:
char *str = "abcdef";
char *ptr;
for(ptr = str; *ptr ; ptr++);
for(; str < --ptr; str++)
{
char c = *str;
*str = *ptr;
*ptr = c;
}
I get a segmentation fault error. And I don't see the mistake (maybe it is too obvious). Any hints?
Cheers
Change
char *str = "abcdef";
to
char str[] = "abcdef";
The first str points to a string literal and string literals are not modifiable in C,
Your string is stored in ROM, so you can't write to it. Depends on your platform though.

char *str vs char str[] : segmentation issue [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.
#include <stdio.h>
#include <conio.h>
void test(char *p)
{
p = p + 1;
*p = 'a';
}
int main()
{
char *str = "Hello";
test(str);
printf("%s", str);
getch();
return 0;
}
When I run this code it gives segmentation error ? why is this happening. The const theory is not clear to me... whereas if I declare str as char str[], it does the job. Are they not both basically the same things ?
str is pointing to a string literal, you are attempting to modify the string literal in the function test on this line:
*p = 'a';
It is undefined behavior to attempt to modify a string literal. You can alternatively, make a copy of the string literal into a array as follows:
char str[] = "Hello";
now it is perfectly ok to modify str. From the draft C99 standard, under section 6.4.5 String literals paragraph 6:
It is unspecified whether these arrays are distinct provided their elements have the
appropriate values. If the program attempts to modify such an array, the behavior is
undefined.
*p = 'a';
The problem is the above statement tries to modify the read only segment. String literal "Hello" resides in read only segment and can not be modified.
char str[] = "Hello";
The above statement copies Hello to str character array and the array contents can be modified.

Runtime error while doing string concatenation

What is the problem with the below program?
main( )
{
char *str1 = "United" ;
char *str2 = "Front" ;
char *str3 ;
str3 = strcat ( str1, str2 ) ;
printf ( "\n%s", str3 ) ;
}
I am not able to compile the above program and it always give me runtime error. I am trying to concatenate the two string. Is there any error in the above program?
Thanks.
Make your char *str1 = "United" as
char str1[<required memory for concatenated resultant string>] = "United".
You need to allocate memory for the destination buffer which is str1. str3 will also receive address of str1 in the result. 'strcat' will not check for space availability in destination buffer (str1). Programmer has to take care of it.
You are trying to modify a string literal, but your compiler (and runtime support) won't let you. When you do so, you are invoking 'undefined behaviour', which is a Bad Thing!™ Anything could happen; it is legitimate for the program to crash. Avoid undefined behaviour.
You need to allocate enough (writable) memory for the strings, maybe like this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "United";
char *str2 = "Front";
char str3[64];
strcpy(str3, str1);
strcat(str3, str2);
printf("%s\n", str3);
return(0);
}
When you declare char *str = "someText", basically, you initialize a pointer to a string constant which can't be changed, and is located somewhere in your computer's memory.
After that by using the function strcat() you are trying to change that string constant, which we said is constant -
Such behavior compiles with no errors, but will cause your program to crash during runtime since const (constant) works during runtime and is not precompiled like #define.
A different solution for you might be,
#include<stdio.h>
#include<string.h>
int main(void) {
char* str1 = "Hello,";
char* str2 = " World";
char str3[30];
strcpy(str3, str1);
strcat(str3, str2);
printf("%s\n", str3);
printf("\n\n\n");
return 0;
}
Hope that helps!
Best of luck in the future!

C : Character swapping [duplicate]

This question already has answers here:
What is the difference between char s[] and char *s?
(14 answers)
Closed 10 years ago.
I need to swap two characters by pointers but when I run this code,the program crashes.
int main(){
char *s1 = "string1";
swap(st,(st+1));
/* BUT THIS CODE WORKS - Whats the problem?
* char s1[] = "string1";
* swap(s1,&s1[1]);
*/
return 0;
}
void swap(char * const ptr1, char * const ptr2){
char temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
char *s1 = "string1";
Because s1 points to a string literal and modifying invokes undefined behaviour in C. That's why this doesn't work.
Whereas in this char s1[] = "string1";
s1 is an array and hence it can be modified.
A string literal may not be modified. You try to modify "string1" in your code which is not allowed. Indeed, many compilers place string literals in a special section that may not be written into.
This line of code creates a string literal which cannot be changed. It is only readable.
char *s1 = "string1";
Any attempt to change it will give you an error.
While your commented example :
char s1[] = "string1";
creates an actual array. This can be edited and used normally.

Resources