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
stra local array:Now, you will have a second problem, is that
strisn’t large enough to holdstr2. So you will need to increase the length of it. Otherwise, you will overrunstr– which is also undefined behavior.To get around this second problem, you either need to make
strat least as long asstr2. Or allocate it dynamically: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: