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

标签 c

  #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/

相关文章:

c - unix 中的系统调用 : directories and files

c++ - 禁用 USB 内存棒的存储功能并自动启动程序

c - 为什么temp指针指向0而不是3?

c - 总线错误与段错误

mysql - 更好更简洁的查询方式..(Mysql + C 语言)

c - 指令在虚拟机中的表示

c++ - c++中如何将字符串转换为string中提到的数据类型

c - 带有 PlayBook NDK 的 libpurple

c - 如何根据 C 中的多个定界符分隔字符串?

c - 通过管道转发时,递归进程树输出不同