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

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.

Related

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

In C, what is the difference between char* and char[]? [duplicate]

This question already has answers here:
What is the difference between char s[] and char *s?
(14 answers)
String literals causing small memory leak?
(4 answers)
Should I free char* initialized using string-literals?
(2 answers)
Closed 4 years ago.
I know that many people asked this but I still have some questions about it.
I read that writing:
char *string = "mystring";
Makes it a read only array of characters, if I were trying to do:
string[0] = 'l';
I would get an error.
When I write:
char string[] = "mystring";
it is saved on the stack, just on the current scope.
what about the char*? is it saved on the heap? or on the stack?
And when I tried writing:
char *string = "mystring";
And then:
string = "mystring2";
it worked, but what happened to the old "mystring" array? is there a memory leak caused by doing this?
what about the char*? is it saved on the heap? or on the stack?
The char* is saved on the stack. But that's just one pointer. The actual string data will be stored in your program's executable (this happens when the program is compiled, it's not the char *string = "mystring"; that puts it there). The assignment to the char* initializes it with the address of "mystring" in your program's binary.
it worked, but what happened to the old "mystring" array? is there a memory leak caused by doing this?
Your executable will contain the content of both the "mystring"; and the "mystring2". When you do the string = "mystring2";, you make that pointer change from pointing to one to pointing to another. There's no memory leak here.

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

What is the difference between these two definitions? [duplicate]

This question already has answers here:
Memory Allocation char* and char[]
(3 answers)
Closed 6 years ago.
What is the difference between these two definitions?
char *string = "MyString";
char string[] = "MyString";
As much as I know, the first one is a pointer to a string.
The first is a pointer to a string literal, the second is an array initialized with the contents of the string literal (which BTW when optimized points exactly to where string points).
The first one lives in the read only segment of the program's memory and thus cannot be modified.
The second one is an array of 9 elements and you can modify any of the 9 elements including the termnating null byte that is not explicitly set in the code in your question.

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