开发者

EXC_BAD_ACCESS When Trying to Perform a strcat Function in C

I have a program I am writing for uni in C, and when my code reaches this line:

strcat("m开发者_JAVA百科d5 ", "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?


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");


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:

  • Provide storage where you can store the new, concatenated result.
  • Makes sure there's enough room in that storage for the resulting string.

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);


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()!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜