Why does scanf("%s") behave strangely with char*? [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 2 years ago.
I was trying to solve this problem
When i create a char * and pass it into scanf:
char* input = "";
scanf("%s", input);
It behaves weirdly.
However, when i change the definition and initalize 1000 chars to \0:
char input[1000] = { '\0' };
It behaves properly. Why is it that way?

I'm guessing you're seeing a segmentation fault. When you declare char* input = "";, you're causing input to be a pointer directed at a string literal. String literals are stored in a read-only section of memory. Therefore, trying to overwrite the data with scanf is an invalid use of memory.
However, when you declare char input[1000];, you've now got an array on the stack, which is a section of memory which can be written to. That's why that code works.

First question is what does this declare?
char* input = "";
That's a single byte in a non-mutable (read-only) area of memory. If you write anything to it, that's undefined behaviour, or something more colloquially described as weird behaviour.
When you re-write it correctly you get a 1000 character buffer and you can read to it without undefined behaviour, provided your input is < 1000 characters.

Related

why does it this c program give segmentation fault [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 10 months ago.
#include <stdio.h>
#include <stdlib.h>
int main() {
char *str="hello";
str[0]='H';
return 0;
}
If I use an array I can do use subscript to assign the first character. What's different about using a char pointer here that causes a segmentation fault?
In this code snippet
char *str="hello";
str[0]='H';
you are trying to change a string literal pointed to by the pointer str. Any attempt to change a string literal results in undefined behavior.
From the C Standard (6.4.5 String literals)
7 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.
So though in C opposite to C++ string literals have types of non-constant arrays it is always better to declare pointers to string literals with the qualifier const.
const char *str="hello";
You could declare a character array initialized by the string literal and change the array itself like
char str[] ="hello";
str[0]='H';
okay, I got the answer from this wiki - https://en.wikipedia.org/wiki/Segmentation_fault#Writing_to_read-only_memory
The char pointer declared like that writes to a read-only segment of the process, editing that gives a segmentation fault (specifically SEGV_ACCERR which is defined as invalid permissions for mapped object (see here)
An array on the other hand similarly allocated will be done so on the stack and so can be edited.

I can't seem to know how to concatenate two char pointer strings using strcat, is it not correct? [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.
I can't concatenate two pointer strings using strcat, is it not possible?
I tried using them like strcat(s1,s2), and strcat(*s1,*s2), and all and it still doesn't work.
char *s1="Hello";
char *s2="Bye";
printf("%s\n",s1);
strcat(s1,s2);
printf("%s",s1);
When I run it prints the first "Hello" that is before the strcat, but the code doesn't display the remaining output and doesn't return 0.
Your approach cannot work, for several reasons:
char *s1="Hello";
s1 points to a read-only string (literal). You cannnot modify it.
strcat(s1,s2);
This cannot work because there is not enough room in s1 to add s2.
Use:
char s1[30]="Hello";
char *s2="Bye";
strcat(s1,s2);
With char s1[30]="Hello"; the compiler allocates an array for 30 charactes and then copies the string "Hello" into that array. Unused elements are set to zero.
With char *s2="Bye"; the compiler makes s2 point to a read-only string, so to make that explicit it is better to write const char *s2="Bye";

C char Array appending Buffer overflow [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.
char *pear = "";
int f=0;
while(f != 20) {
pear[f] = 'a';
f++;
}
So I want to append a's to the char string
Why is this causing a buffer problem
And I can't use the strcat I have don't like this.
Having a string initialized as
char * pear = "";
prohibits it from being modified. In contrast,
char pear [] = "";
allows you to modify byte 0 (but not subsequent bytes) afterwards without getting an error. However, since the last byte in the string needs to be 0, it is not a good idea to overwrite it.
More importantly, you are trying to give values up to 20th element - you need space for at least 21 elements. Also, be careful with the terminating character - you need the last element in the array to be 0 for it to be a string. Right now it seems that you are just trying to write characters into the array without terminating it properly.
If you don't know the size of your array up front, you can use dynamic memory allocation: malloc, realloc (and don't forget to free at the end).

Segmentation Fault in char pointer [duplicate]

This question already has answers here:
Modify a string with pointer [duplicate]
(4 answers)
Closed 5 years ago.
I am getting segmentation fault when running the below code. What could be the reason for this error? Please help
int main()
{
char *str2 = "Hello";
str2[3] = 'J';
printf("%s\n",str2);
return 0;
}
It is a undefined behaviour because you are trying to modify the content of a string literal. A string literal mainly stored in a read only location. so you do not modify it, otherwise it is invoked undefined behaviour.
C11 ยง6.4.5 String literals(Paragraph 7):
It is unspecified whether these arrays are distinct provided their
elements have the appropriate values.If the program attempts to
modify a string literal of either form, the behavior is undefined"
You aren't allowed to modify a string constant, and in this case it's causing a runtime error. You can fix it by changing the declaration of str2 to:
char str2[] = "Hello";
This makes it an array, rather than a pointer to a string constant.
You are not allowed to modify the memory pointed to by char* variables initialized with string literals. It is read-only.

stripping end of a 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)
Is modifying a string pointed to by a pointer valid?
(9 answers)
Closed 9 years ago.
I need a function to remove ) character from end of a string.
for example, hello,world) should be converted to hello,world.
I have written this :
char *a="hello,world)";
int a_len=strlen(a);
*(a+a_len-1)='\0';
printf("%s", a);
but nothing is shown in the output.
You should ideally be getting a segmentation violation runtime error.
You have assigned a pointer to a string literal which resides in read-only memory. Trying to modify that is bad!
Try copying it onto the stack
char a[] ="hello,world)";
If you really have to use dynamic memory (please write that in your question) then you have to manually copy your string there:
char *a = malloc(sizeof("hello,world)"));
memcpy(a, "hello,world)", sizeof("hello,world)"));
int a_len=strlen(a);
a[a_len - 1] = '\0';
Alternatively you can also have printf truncate your string:
printf("%.*s", strlen(a) - 1, a);
Also as Basile pointed out there is strdup
char * a = strndup("hello,world)", sizeof("hello,world)") -2);
Note that here we have to truncate by two characters because sizeof includes the null terminator, but strndup will always add one.
Analysis:
Line #1: char *a="hello,world)";
Variable a points to an array of characters, located in the (read-only) code section of the program
Line #3: *(a+a_len-1)='\0';
A memory access violation occurs, when the CPU attempts to write into a read-only memory section
Solution:
Line #1: char a[]="hello,world)";
Variable a is an array of characters located in the stack of the program, which is a read/write section
I must use dynamic memory so I have to leave char[].
trying this also does not work:
char *a=malloc(4);
a="hello,world)";
int a_len=strlen(a);
*(a+a_len-2)='\0';
printf("%s", a);

Resources