What is the meaning of Bus: error 10 in C
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 befree()
'ed - you need to allocate
n + 1
bytes for a string which is of lengthn
(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;
}
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>