char *str vs char str[] : segmentation issue [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 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.

Related

C program - causes crash with 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.
in this C program when i am using
printf("%c",*(name+5));
then program works fine but when i am using
*(name+5) = '#';
then program causes crash
#include <stdio.h>
void main(void)
{
char * name;
name ="Hello World !";
puts(name);
*(name+5) = '#'; // here is error
puts(name);
}
With...
char * name;
name ="Hello World !";
*(name+5) = '#';
you are manipulating the contents of a string literal, which is undefined behaviour, likely a crash.
Make an array out of it, which you may alter then:
char name[] ="Hello World !";
name[5] = '#';
or:
char buffer[] ="Hello World !";
char *name = buffer;
*(name+5) = '#';
Note that here the contents of string literal "Hello World!" are copied into an array which's content you are allowed to change.

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[]”?

how to assign value to pointer string in C [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.
In C language I am trying to assign a value to pointer string. I cannot use char array, I have to use pointer string. So please tell how can I do that?
I am doing something like this (code given), but when I run my code an error is prompted program stopped working.
#include <stdio.h>
int main (void) {
char *myString = " ";
int value = 1;
myString[0] = value+'0';
printf("%s\n",myString);
return 0;
}
You cannot modify a string literal: myString is initialized to point to constant storage for the string literal. Attempting to modify it invokes undefined behavior. Use strdup() to create a copy of the string:
#include <stdio.h>
#include <string.h>
int main(void) {
char *myString = strdup(" ");
int value = 1;
myString[0] = value + '0';
printf("%s\n", myString);
free(myString);
return 0;
}
strdup() is a function standardized in POSIX, that allocates a block of memory from the heap long enough to receive a copy of its string argument. It copies the string into it and returns a pointer to the block. Such a block can be modified, and should be freed with free() when no longer needed.

Replace individual character element of a string C [duplicate]

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.

Segmentation fault (core dumped) in strtok [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Memory Allocation char* and char[]
Why does the following program give a Segmentation fault in run-time ?
#include <stdio.h>
#include <string.h>
#include <malloc.h>
main()
{
char * str = "Have a. nice, day :)";
char * ptr;
ptr = strtok( str, " .,");
printf("%s",ptr);
}
But if I use char str[] = "Have a. nice, day :)"; it gives me the output. Why is that i get the error even though strtok definition is char* strcpy( char * , const char * ) ???~
strtok modifies the argument, str points to a string literal, modifying a string literal causes undefined behavior. Initializing a non-const char* with a string literal is in fact deprecated.
When you write str[], str becomes a mutable array initialized with the string.
strtok modifies the string passed to it. I suspect it has something to do with char * = "literal string" giving you a pointer to the string in the .data section, while char[] = "literal string" allocates a buffer on the stack, and copies the initial contents from the .data section.

Resources