繁体   English   中英

powerPC中的pclose问题

[英]pclose issue in powerPC

我正在为嵌入式系统创建一个应用程序,该应用程序使用popen运行/ usr / bin / find,但是遇到一个奇怪的问题,我的代码就像...

int main() {
  char str[2048]
  fun1(str, 2048);
  return 0;
}

int fun1(char* str, int cap) {
   return fun2(str,<command>, cap);
}

int fun2(char* str, char* cmd, int cap) {
  FILE* fptr = popen(cmd, "r");
  char line_buffer[2048];
  int total = 0;
  int count = 0;
  str[0] = '\0';

  while (count = (fgets(line_buffer, sizeof(line_buffer), fptr)) != 0) {
    total += count;
    strcat(str, line_buffer);
  }

  pclose(fptr);
  return total;

}

调用pclose时,我的应用程序将返回到main,就像再次调用main()一样,这仅在PowerPC上发生,而在ARM设备上不发生,为什么?

我的应用程序返回到main,好像再次调用了main()一样

如果要赌博,我会说您的代码崩溃了,您看到的实际上是一个自动软复位。

但是为什么程序崩溃?

我认为这是因为您在没有任何绑定检查的情况下调用strcat() 您读取的每一行可以长达2048个字节,而整个串联的字符串也只有2048个字节长。

可能刚好将您的缓冲区定义为与FILE *fptr太近,因此它将覆盖它,并且pclose()试图关闭无效的处理程序并崩溃。

验证这是问题所在,请尝试将char str[2048]更改为char str[65536]然后查看它是否可以重现。

解决此问题,请使用更安全的strncat而不是strcat以避免内存损坏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM