gpt4 book ai didi

c - 这个脚本哪里有错误?

转载 作者:行者123 更新时间:2023-11-30 21:16:45 24 4
gpt4 key购买 nike

  #include <string.h>
#include <stdio.h>

char *string = "<aa>RRRR|<aa>SSS|";
char *cmp = "<aa>";
char *p1;
int nlen;

main()
{
while ( p1 = strstr(string, "<aa>") ) {
nlen = 0;
p1 = p1 + 4;
while ( ( *p1 != '|' ) && ( *p1 != '\0') ) { p1 = p1 + 1; nlen++; };
p1 = p1 - nlen;
string = p1 + 1;
char rr[200];
strncpy(rr,p1,nlen);
printf("%s\n", rr);
}
}

错误答案:

RRRR
SSSR

最佳答案

您缺少一个空字符来终止字符串。来自维基百科关于 strncpy 的文章.

strncpy writes exactly the given number of bytes, either only copying the start of the string if it is too long, or adding zeros to the end of the copy to fill the buffer. It was introduced into the C library to deal with fixed-length name fields in structures such as directory entries. Despite its name it is not a bounded version of strcpy, it does not guarantee that the result is a null-terminated string. The name of the function is misleading because strncat and snprintf are respectively bounded versions of strcat and sprintf.

添加空字符使您的程序正常运行:

strncpy(rr, p1, nlen);
*(rr+nlen) = '\0'; // this line
printf("%s\n", rr);

我认为您的代码可能存在缓冲区溢出的风险,因为 nlen 理论上可能大于 200。尽管这在您的问题中的程序中不是问题,因为输入字符串是如此短。

您可能还想查看strncat它可用于复制包含空字符的字符串。

An alternative from the standard C library that will always append one null byte is to use strncat with an initially empty string as the destination.

关于c - 这个脚本哪里有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3485224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com