Runtime error while doing string concatenation - c

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!

Related

Segmentation fault in my strcpy

I'm writing my own strcpy due to the fact that the default one in string.h only accept a const char * as a source string to copy from.
I'm trying this very basic prototype (yes, the return isn't meaningful, I'm just trying things):
int copyStrings(char * dest, char * source){
int i=0;
while(source[i]!='\0'){
dest[i]=source[i];
i++;
}
dest[i]='\0';
return 0;
}
and it gives me SIGSEGV, Segmentation Fault error in gdb, at the line dest[i]=source[i], right at the first character. I'm pretty sure dest[i] isn't a string literal, so I should be able to modify it.
What am I doing wrong?
EDIT: here's the calling
int main(){
char * str = (char*)malloc((int)sizeof(double));
char * str2 = (char *)malloc((int)sizeof(int));
str = "hello";
str2 = "hey jude";
copyStrings(str2, str);
free(str);
free(str2);
return 0;
}
This is assigning a string literal to str2 - the very thing that you claim you aren't doing. This is actually the cause of your segfault.
str2 = "hey jude";
It also is causing a memory leak as prior to this, you malloc'd some memory and assigned it to str2 as well. But not enough memory to hold the string. Typically an int is 4 bytes and you need 9 bytes to store that string.
What you want to do is this, which allocates as many bytes as there are in the string, plus an extra one to store the \0 terminating character at the end.
str2 = malloc(strlen("hey jude")+1);
strcpy(str2,"hey jude");
or on some systems you can use POSIX function strdup() which effectively does the job of the above in one handy function call.
str2 = strdup("hey jude");
Let's go at it line by line and see where it goes wrong:
int main(){
char * str = (char*)malloc((int)sizeof(double));
char * str2 = (char *)malloc((int)sizeof(int));
str = "hello";
str2 = "hey jude";
copyStrings(str2, str);
free(str);
free(str2);
return 0;
}
int main(){ - this is an improper definition of main. Should be int main(int argc, char **argv)
char * str = (char*)malloc((int)sizeof(double)); - defines str, then allocates (probably) 8 bytes of memory and assigns its address to str. malloc takes a size_t argument, so the cast (int)sizeof(double) is incorrect. Also, in C the return value of malloc should never be cast. So this line should be char * str = malloc(sizeof(double));
char * str2 = (char *)malloc((int)sizeof(int)); - all the same problems as the preceding line. Should be char *str2 = malloc(sizeof(int));
str = "hello"; - causes a memory leak, because the memory you JUST ALLOCATED two lines earlier is now irretrievably lost. You've got two options here - either don't allocate the memory when defining str or free it first. Let's do the latter:
free(str);
str = "hello";
str2 = "hey jude"; - same problem, similar solution:
free(str2);
str2 = "hey jude";
copyStrings(str2, str); - here you're telling your routine to copy the constant string "hello" over the top of the constant string "hey jude". This will work fine on some systems, but will blow up on other systems. The question is in the treatment of the constant string "hey jude". If it's stored in modifiable memory the code will work just fine. If it's stored in memory which is marked as being unmodifiable, however, it will blow up. It seems that the latter is the case on your system. To fix this you probably want to go back to the previous line and change it to
str2 = malloc(20);
That's more memory than you'll need, but it will work just fine.
free(str); - you're attempting to free the constant string "hello", which is not dynamically allocated memory. This needed to be done prior to the assignment str = "hello";.
free(str2; - same problem as above. This needed to be done prior to the assignment str2 = "hey jude";.
} - correct
Best of luck.

String concatenation. C

All of the code below on C.
Both the code snippet below are compiled, but the difference is that the second program crashes at startup.
One:
#include <stdio.h>
#include <string.h>
void main() {
char *foo = "foo";
char *bar = "bar";
char *str[80];;
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
}
Two:
#include <stdio.h>
#include <string.h>
void main() {
char *foo = "foo";
char *bar = "bar";
char *str="";
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
}
The difference is that in the first case, said the size of the str string, while the second is not. How to make string concatenation without a direct indication of the size of the string str?
The difference is that in the first case, said the size of the str
string, while the second is not.
No. In the first program, the following statement
char *str[80];
defines str to be an array of 80 pointers to characters. What you need is a character array -
char str[80];
In the second program,
char *str="";
defines str to be a pointer to the string literal "", not an array. Arrays and pointers are different types.
Now, the second program crashes because
char *str="";
defines str to be a pointer to a string literal. The first argument of strcpy should be a pointer to a buffer which is large enough for the string to be copied which is pointed to by its second argument.
However, str points to the string literal "" which is allocated in read-only memory. By passing str to strcpy, it invoked undefined behaviour because strcpy tries to modify it which is illegal. Undefined behaviour means the behaviour is unpredictable and anything can happen from program crash to due to segfault (illegal memory access) or your hard drive getting formatted. You should always avoid code which invoked undefined behaviour.
How to make string concatenation without a direct indication of the
size of the string str?
The destination string must be large enough to store the source string else strcpy will overrun the buffer pointed to by its first argument and invoke undefined behaviour due to illegal memory access. Again, the destination string must have enough space for the source string to be appended to it else strcat will overrun the buffer and again cause undefined behaviour. You should ensure against this by specifying the correct size of the string str in this case.
Change to:
One:
#include <stdio.h>
#include <string.h>
void main() {
char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
}
Two:
#include <stdio.h>
#include <string.h>
void main() {
char *foo = "foo";
char *bar = "bar";
char str[80]="";
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
}
#include <stdio.h>
#include <string.h>
void main() {
char *foo = "foo";
char *bar = "bar";
char *str=NULL;
size_t strSize = strlen(foo)+strlen(bar)+strlen("TEXT ")+1;
str=malloc(strSize);
if(NULL==str)
{
fprintf(stderr, "malloc() failed.\n");
goto CLEANUP;
}
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
CLEANUP
if(str)
free(str);
}
size_t len1 = strlen(first);
size_t len2 = strlen(second);
char * s = malloc(len1 + len2 + 2);
memcpy(s, first, len1);
s[len1] = ' ';
memcpy(s + len1 + 1, second, len2 + 1); // includes terminating null
Did I do good?
In the second version you have set char *str=""; this is equivalent to allocating an empty string on the stack with 1 byte which contains null for end of string. Had you written char*str="0123456789", you would have allocated 11 bytes on the stack the first 10 of which would have been "0123456789" and the 11th byte would have been null. If you try to copy more than allocated bytes to the str, your program might crash. So either allocate dynamically enough memory, or statically.
Both programs are wrong, the first provokes undefined behavior exactly as the second one.
char *str[80]; is array of pointers which you pass to functions ( strcpy, strcat) as first argument, while the first argument for those functions should be char *. Possible solution for this issue to define str as char str[80];
The issue with the second program is that char *str=""; is a pointer to read only piece of memory, which can't be changed.In this case one of possible solutions can be :
char* str = malloc(80);
strcpy(str,"");
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
You'll have to allocate memory before copying. The first defines the size so as 80
char *str = new char[10]; could also be a method of allocation. malloc function could also be used to allocate memory.
Here are some references that might help you
http://www.cplusplus.com/reference/cstdlib/malloc/
http://www.cplusplus.com/reference/cstdlib/calloc/

Concatenate two char* strings in a C program

I wrote the following C program:
int main(int argc, char** argv) {
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
printf("%s", strcat(str1, str2));
return (EXIT_SUCCESS);
}
I want to concatenate the two strings, but it doesn't work.
The way it works is to:
Malloc memory large enough to hold copies of str1 and str2
Then it copies str1 into str3
Then it appends str2 onto the end of str3
When you're using str3 you'd normally free it free (str3);
Here's an example for you play with. It's very simple and has no hard-coded lengths. You can try it here: http://ideone.com/d3g1xs
See this post for information about size of char
#include <stdio.h>
#include <memory.h>
int main(int argc, char** argv) {
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
char * str3 = (char *) malloc(1 + strlen(str1)+ strlen(str2) );
strcpy(str3, str1);
strcat(str3, str2);
printf("%s", str3);
return 0;
}
Here is a working solution:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
char str1[16];
char str2[16];
strcpy(str1, "sssss");
strcpy(str2, "kkkk");
strcat(str1, str2);
printf("%s", str1);
return 0;
}
Output:
ssssskkkk
You have to allocate memory for your strings. In the above code, I declare str1 and str2 as character arrays containing 16 characters. I used strcpy to copy characters of string literals into them, and strcat to append the characters of str2 to the end of str1. Here is how these character arrays look like during the execution of the program:
After declaration (both are empty):
str1: [][][][][][][][][][][][][][][][][][][][]
str2: [][][][][][][][][][][][][][][][][][][][]
After calling strcpy (\0 is the string terminator zero byte):
str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
After calling strcat:
str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
strcat concats str2 onto str1
You'll get runtime errors because str1 is not being properly allocated for concatenation
When you use string literals, such as "this is a string" and in your case "sssss" and "kkkk", the compiler puts them in read-only memory. However, strcat attempts to write the second argument after the first. You can solve this problem by making a sufficiently sized destination buffer and write to that.
char destination[10]; // 5 times s, 4 times k, one zero-terminator
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
strcpy(destination, str1);
printf("%s",strcat(destination,str2));
Note that in recent compilers, you usually get a warning for casting string literals to non-const character pointers.
strcat(str1, str2) appends str2 after str1. It requires str1 to have enough space to hold str2. In you code, str1 and str2 are all string constants, so it should not work. You may try this way:
char str1[1024];
char *str2 = "kkkk";
strcpy(str1, "ssssss");
strcat(str1, str2);
printf("%s", str1);
strcat attempts to append the second parameter to the first. This won't work since you are assigning implicitly sized constant strings.
If all you want to do is print two strings out
printf("%s%s",str1,str2);
Would do.
You could do something like
char *str1 = calloc(sizeof("SSSS")+sizeof("KKKK")+1,sizeof *str1);
strcpy(str1,"SSSS");
strcat(str1,str2);
to create a concatenated string; however strongly consider using strncat/strncpy instead. And read the man pages carefully for the above. (oh and don't forget to free str1 at the end).

Can I copy a string in an empty string?

Suppose I do like this to copy the string.
char str[] = "";
char *str2 = "abc";
strcpy(str, str2);
printf("%s", str); // "abc"
printf("%d", strlen(str)); // 3
Then, why it doesn't give me undefined behaviour or causing the program to fail. What are the disadvantages of doing like that ?
You are writing past the memory space allocated to str on the stack. You need to make sure you have the correct amount of space for str. In the example you mentioned, you need space for a, b, and c plus a null character to end the string, so this code should work:
char str[4];
char *str2 = "abc";
strcpy(str, str2);
printf("%s", str); // "abc"
printf("%d", strlen(str)); // 3
This code is definitely causing a stack problem, though with such a small string, you are not seeing the issue. Take, for example, the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[] = "";
char *str2 = "A really, really, really, really, really, really loooooooooooooooonnnnnnnnnnnnnnnnng string.";
strcpy(str, str2);
printf("%s\n", str);
printf("%d\n", strlen(str));
return 0;
}
A contrived example, yes, but the result of running this is:
A really, really, really, really, really, really loooooooooooooooonnnnnnnnnnnnnnnnng string.
92
Segmentation fault
This is one of the reasons why the strcpy function is discouraged, and usage of copy and concatenate functions that require specifying the sizes of the strings involved are recommended.
It actually gives you undefined behavior, but your program doesn't have to fail because of that. That's how undefined behavior works.

What is the meaning of Bus: error 10 in C

Below is my code
#import <stdio.h>
#import <string.h>
int main(int argc, const char *argv[])
{
char *str = "First string";
char *str2 = "Second string";
strcpy(str, str2);
return 0;
}
It compiles just fine without any warning or errors, but when I run the code I get the error below
Bus error: 10
What did I miss ?
For one, you can't modify string literals. It's undefined behavior.
To fix that you can make str a local array:
char str[] = "First string";
Now, you will have a second problem, is that str isn't large enough to hold str2. So you will need to increase the length of it. Otherwise, you will overrun str - which is also undefined behavior.
To get around this second problem, you either need to make str at least as long as str2. Or allocate it dynamically:
char *str2 = "Second string";
char *str = malloc(strlen(str2) + 1); // Allocate memory
// Maybe check for NULL.
strcpy(str, str2);
// Always remember to free it.
free(str);
There are other more elegant ways to do this involving VLAs (in C99) and stack allocation, but I won't go into those as their use is somewhat questionable.
As #SangeethSaravanaraj pointed out in the comments, everyone missed the #import. It should be #include:
#include <stdio.h>
#include <string.h>
There is no space allocated for the strings. use array (or) pointers with malloc() and free()
Other than that
#import <stdio.h>
#import <string.h>
should be
#include <stdio.h>
#include <string.h>
NOTE:
anything that is malloc()ed must be free()'ed
you need to allocate n + 1 bytes for a string which is of length n (the last byte is for \0)
Please you the following code as a reference
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
//char *str1 = "First string";
char *str1 = "First string is a big string";
char *str2 = NULL;
if ((str2 = (char *) malloc(sizeof(char) * strlen(str1) + 1)) == NULL) {
printf("unable to allocate memory \n");
return -1;
}
strcpy(str2, str1);
printf("str1 : %s \n", str1);
printf("str2 : %s \n", str2);
free(str2);
return 0;
}
str2 is pointing to a statically allocated constant character array. You can't write to it/over it. You need to dynamically allocate space via the *alloc family of functions.
string literals are non-modifiable in C
Your code attempts to overwrite a string literal. This is undefined behaviour.
There are several ways to fix this:
use malloc() then strcpy() then free();
turn str into an array and use strcpy();
use strdup().
this is because str is pointing to a string literal means a constant string ...but you are trying to modify it by copying .
Note : if it would have been an error due to memory allocation it would have been given segmentation fault at the run time .But this error is coming due to constant string modification or you can go through the below for more details abt bus error :
Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:
using a processor instruction with an address that does not satisfy
its alignment requirements.
Segmentation faults occur when accessing memory which does not belong to your process, they are very common and are typically the result of:
using a pointer to something that was deallocated.
using an uninitialized hence bogus pointer.
using a null pointer.
overflowing a buffer.
To be more precise this is not manipulating the pointer itself that will cause issues, it's accessing the memory it points to (dereferencing).
Let me explain why you do you got this error "Bus error: 10"
char *str1 = "First string";
// for this statement the memory will be allocated into the CODE/TEXT segment which is READ-ONLY
char *str2 = "Second string";
// for this statement the memory will be allocated into the CODE/TEXT segment which is READ-ONLY
strcpy(str1, str2);
// This function will copy the content from str2 into str1, this is not possible because you are try to perform READ WRITE operation inside the READ-ONLY segment.Which was the root cause
If you want to perform string manipulation use automatic variables(STACK segment) or dynamic variables(HEAP segment)
Vasanth
Whenever you are using pointer variables ( the asterix ) such as
char *str = "First string";
you need to asign memory to it
str = malloc(strlen(*str))
None of the mentioned solution, worked for me as I couldn't find where the error was coming from. So, I simply deleted my node_modules and re-installed it. And the error disappeared; my code started working again

Resources