Reputation: 25652
I have a program I am writing for uni in C, and when my code reaches this line:
strcat("md5 ", "blah");
I am getting a EXC_BAD_ACCESS error, and my app crashes. As far as I can tell, there isn't anything wrong with it, so I thought a fresh pair of eyes might solve my problem. Any ideas?
Upvotes: 3
Views: 1470
Reputation: 229204
In C, you have to provide the space of where to store something yourself. "md5 " has only room for 4 characters (+ a nul terminator). There is not enough space to append "blah" there.
More important, you cannot modify a string literal. They are usually read only. So, you have to:
E.g.:
char result[9]; //the result here needs 8 characters + a nul terminator
strcpy(result,"md5 ");
strcat(result,"blah"
Or, e.g.
const char *a = "md5 ";
const char *b = "blah";
char *result = malloc(strlen(a) + strlen(b) + 1);
if(result == NULL) {
out of memory
return;
}
strcpy(result,a);
strcat(result,b);
Upvotes: 3
Reputation: 4179
According to http://www.cplusplus.com/reference/clibrary/cstring/strcat/ :
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a new null-character is appended at the end of the new string formed by the concatenation of both in destination.
Since your first string is a constant, you don't know where it is in memory and you aren't allowed to play with the memory that follows it.
Upvotes: 1
Reputation: 86403
The first string supplied to strcat needs to be a writable buffer with enough space for the second string past its current contents. That means that you cannot use string literals as the first argument for strcat()!
Upvotes: 1
Reputation: 34734
You're trying to modify a constant string. The first argument of strcat
is also the destination string and in your case it is a constant string. You should use something like:
char s[100];
strcpy(s, "md5 ");
strcat(s, "blah");
Upvotes: 8