Does strlen have any side effect?

时间:2017-11-08 22:12:26

标签: c++ c

I know, or better I suppose, that strlen() is fairly simple function, but for some reason, when I want to use it in one my function, it will corrupt the program. I have no idea why it's happening, because the results from strlen are correct, but the program as a whole doesn't work if strlen is included. To be specific, this part of code is causing trouble:

int random1 = strlen(objectNameValue);
int random2 = strlen(PA_type_value);
int random3 = strlen(attributeValue);
printf("length of objectNameValue: %d, PA_type_value: %d, attributeValue: %d", random1, random2, random3);

My program is actually a simple LDAP server and I'm trying to send some data - those variables (attributeValue), for example, when I put this part of code to comments, it works perfectly. But if I leave it there, sent data are not correct, and I have really no idea how strlen can affect them. Funny is that strlen is actually printing correct results.

To specify a bit more, those three variables in strlen are all of type char[] and all have /0 at the end. Can anyone help?

So, after request in comments, here is a closer look: Basically, in very minimal way, this is something I'm doing:

char message_out[1024];
bzero(message_out, 1024);
char objectNameValue[1024];
strcpy(objectNameValue,"cn=");
char PA_type_value[5] = {'u', 'i', 'd'};
strcat(Message_out, objectNameValue);
strcat(Message_out, PA_type_value);

But sometimes I'm not putting the fixed characters into string, but another string for example., and I need to find out how big that string is, because I need to count total lengths of the message_out. I always watch out for strings, to be big enough, to be initialized with zeroes.

Output is this:

Length of objectNameValue: 12, PA_type_value: 3, attributeValue: 8

1 个答案:

答案 0 :(得分:1)

问题可能在于strlen如何找到长度。 strlen遍历字符数组的所有字符,直到找到终端\ 0字符。如果数组没有此终端字符,则实现可能会从您给它的字符数组的内存边界开始,并导致未定义的行为。