strncpy的第三个参数更改了我的局部变量
如您所见,我初始化的最大大小为1000。当MAX_SIZE不大于buffer时,MAX_SIZE变为零。 代码的输出如下所示:strncpy的第三个参数更改了我的局部变量,c,out-of-memory,c-strings,strncpy,null-character,C,Out Of Memory,C Strings,Strncpy,Null Character,如您所见,我初始化的最大大小为1000。当MAX_SIZE不大于buffer时,MAX_SIZE变为零。 代码的输出如下所示: char activeip[11]="0123456789"; char buffer[1001]; int MAX_SIZE = 1000; printf("MAX_SIZE %d\n", MAX_SIZE); strncpy(buffer, "string here....... ",MAX_SIZ
char activeip[11]="0123456789";
char buffer[1001];
int MAX_SIZE = 1000;
printf("MAX_SIZE %d\n", MAX_SIZE);
strncpy(buffer, "string here....... ",MAX_SIZE+1);
printf("MAX_SIZE %d\n", MAX_SIZE);
strncpy(&buffer[strlen(buffer)],activeip,MAX_SIZE+1 );
printf("MAX_SIZE %d\n", MAX_SIZE);
strncpy(&buffer[strlen(buffer)],"Long string here.....................................", MAX_SIZE+1);
printf("MAX_SIZE %d\n", MAX_SIZE);
puts(buffer);
函数(strncpy)如何更改为我的局部变量(MAX_SIZE)?
我的编译器正在CLion上运行
感谢您对这些电话的回复
MAX_SIZE 1000
MAX_SIZE 0
MAX_SIZE 0
string here....... 0123456789L
Process finished with exit code 0
及
将第一个参数指向的数组追加为MAX_SIZE+1减去复制字符串的长度,并加上零
根据C标准(7.23.2.4 strncpy功能)
3如果s2指向的数组是短于n的字符串
字符,null字符追加到数组中的副本
由s1指向,直到总共写入n个字符。
因此,数组缓冲区之外的内存被覆盖。您需要更改第三个参数的值,使其更小(考虑复制字符串的长度和字符数组中使用的偏移量)。关于以下语句:
strncpy(&buffer[strlen(buffer)],"Long string here.....................................", MAX_SIZE+1);
这不是附加activeip
字符串的好方法。建议:
strncpy(&buffer[strlen(buffer)],activeip,MAX_SIZE+1 );
或
如果您的代码有未定义的行为,它可以更改您的局部变量,在这种情况下是因为缓冲区溢出,它恰好运行到表示
MAX\u SIZE
的字节中。请确保避免UB:-)@下划线\u d感谢您的帮助:)这是我第一次看到函数影响我的局部变量。我很惊讶。在那之后,我会注意的。谢谢你的帮助。我从MAX_SIZE中减去了字符串的长度。然后把它放在第三个论点中。现在它工作正常了!
strncpy(&buffer[strlen(buffer)],activeip,MAX_SIZE+1 );
strcat( buffer, activeip );
strncat( buffer, activeip, sizeof(buffer) - strlen buffer );