Search code examples
carmembeddedpowerpc

pclose issue in powerPC


i was creating an application for an embedded system, which uses popen to run /usr/bin/find, however i came across a weird issue, my code was something like...

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;

}

when pclose is called, my application goes back to main as if main() was called again, this only happens on PowerPC but not on ARM devices, why is this?


Solution

  • my application goes back to main as if main() was called again

    If I had to take a gamble, I would say that your code crashes and what you see is actually an automatic soft-reset.

    But why does the program crash?

    I would deem that this happens because you call strcat() without any bound checking. Each line you read can be as long as 2048 bytes, whereas the entire concatenated string is also only 2048 bytes long.

    It might just happen that your buffer is defined too close to FILE *fptr, thus it overrides it and pclose() tries to close an invalid handler and crashes.

    To verify that this is the problem try changing char str[2048] to char str[65536] and see if it reproduces.

    To fix the issue, use the safer strncat instead of strcat to avoid memory corruptions.