-
Strange string behavior
Perhaps I'm doing this wrong but I'm getting weird behavior. Basically I have a prefix string, I copy it into a larger message. Then I print it's length which is correct. Then I try and add a bunch of letter a's onto the end of the message. My thought would be that the length of the message would increase by 1 everytime however I have output that looks like this:
.
.
.
message has length 1990
message has length 1991
message has length 1994
message has length 1994
message has length 1994
message has length 1995
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2017
message has length 2018
message has length 2019
message has length 2056
message to send is 2056
There are sections where numbers are skipped or repeated. This doesn't really make sense to me.
Code:
char *prefix = "12345678901234";
char message[2048];
strcpy(message,prefix);
printf("message prefix is %s with length %d\n",message,strlen(message));
int i = strlen(message);
while(strlen(message)<=2048)
{
message[i]='a';
i++;
printf("message has length %d\n",strlen(message));
}
-
Well, message is uninitialized, so it is filled with garbage data. strlen reads length to null-terminator. You are just inserting an 'a' at the end, and not adding a '\0' after it, so strlen might go past the 'a' you added and stop at whatever '\0' was left in memory.
-
That makes sense. I'm still getting used to C. I did a memset and set everything to \0 first and it worked. Thanks!