I'm implementing a basic string copy function in c like so:
void copy(char* src, char* dst) {
while (*src) {
*dst = *src;
dst++, src++;
}
}
I call it like so:
int main(int argc, char* argv[]) {
char* src = "Hello World!";
char* dst = "AAAAAAAAAAAA";
printf("Source: %s | Des: %s\n", src, dst);
copy(src, dst);
printf("Source: %s | Des: %s", src, dst);
}
When debugging with lldb, I know for a fact that src and dst in copy are valid pointers. And yet, when *dst = *src
executes, my program gets thrown a BAD_ACCESS_ERR. How is this even possible? The compiler should be statically allocating the memory for src and dst. Both are of equal sizes in terms of string lengths. The error doesn't even get thrown on the null-terminating character, it gets thrown on the first time the assign statement executes. What am I not seeing? Is this macOS specific?
char* dst = "AAAAAAAAAAAA";
You define destination to point to a section of memory that could be read only -- string literals are allowed by the C standard to be kept into a read only segment. 6.4.5p6 String literals
:
You need to define the destination in heap or into a vector, that you are sure to allocate correctly.
dst = malloc(SIZE);
or
char dst[100];
In the first case make sure you call free, in the second case make sure you do not access it after its scope or the source does not have more than 99 characters+NUL.