C char Array appending Buffer overflow [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 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).

Related

Why does scanf("%s") behave strangely with char*? [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 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.

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";

Why does the strcat function give me a segmentation fault? [duplicate]

This question already has answers here:
How do I concatenate two strings in C?
(12 answers)
How do I concatenate const/literal strings in C?
(17 answers)
Closed 4 years ago.
I want to concatenate "/bin/" and "touch" so that I will have "/bin/touch".
In my program, I have
char* filePath = malloc((strlen("/bin/") + strlen(rv[0]))* sizeof(char));
filePath = strcat("/bin/",rv[0])
First of all, rv[0] contains a string, "touch". I allocate 10 bytes in memory by using malloc function, and filePath will be the pointer to those 10 bytes of memory. Because, the total length of the string concatenated ("/bin/touch") will be 10.
The program executes normally until the second line which gives me a segmentation fault. Did I make any mistake on the strcat function?
Take a look at the reference for how to use strcat:
char *strcat( char *dest, const char *src );
Appends a copy of the null-terminated byte string pointed to by src to the end of the null-terminated byte string pointed to by dest.
The first parameter must thus be a pointer to a memory location large enough to hold the bytes of both the C string already there and the C string pointed to by src.
You call strcat("/bin/",rv[0]) and thus try to write into memory where the string literal "/bin/" is stored .. which is normally in readonly memory, thus You get a segmentation fault.
You need to copy "/bin/" first into the allocated memory pointed to by filePath and then append rv[0] there.

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);

pointers and string [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 years ago.
int main()
{
char *ch="girl";
int x=strlen(ch);
*ch=ch[x];
printf("%c",*ch);
getch();
return 0;
}
Why there is a runtime error during the assignment of a NULL value to the pointer to character?
Replace
char *ch = "girl"
with
char ch[] = "girl"
Where the former creates a pointer to immutable memory, the latter creates a char[] array of the right size and initialises it with the letters of "girl" (including the terminating zero-byte).
UPDATE: thanks to #dreamlax
"girl" is implicitly declared as a char *. But most likely your compiler is putting the string-literals into a section (rostrings) which will later be placed in a protected memory-area. When you try to assign something to *ch it will access this protected (or not depending on your platform) memory.
The compiler should warn you about the char *ch = "girl";.
And this
int x=strlen(ch); //x=4
*ch=ch[x]; //you are out of bounds of array, because first element is 0, so last is 3

Resources