'how to detect div0 error in a auto generate expression

I need to auto generate some expression such as "(1+2)/3*4" for unit test. Here is my main frame. The idea is auto-generate a expr using gen_rand_expr(), save it to a tmp.c file, and get expr result, finally save some expr and its result to a file.

static char buf[65536] = {'\0'};
static char code_buf[65536 + 128] = {};

// writing it to a tmp.c file
static char *code_format =
"#include <stdio.h>\n"
"int main() { "
"  unsigned result = %s; "
"  printf(\"%%u\", result); "
"  return 0; "
"}";

int main(int argc, char *argv[]) {
  if (argc > 1) {
    sscanf(argv[1], "%d", &loop);
  }
  int i;
  for (i = 0; i < loop; i ++) {
    // a recursive function writing a expr string to 'buf'
    gen_rand_expr();
    // writing auto-generate expr into code_buf
    sprintf(code_buf, code_format, buf);
    // save code buf as a tmp c file
    FILE *fp = fopen("/tmp/.code.c", "w");
    assert(fp != NULL);
    fputs(code_buf, fp);
    fclose(fp);
    // compile the c file to get expresion result
    int ret = system("gcc /tmp/.code.c -o /tmp/.expr");
    if (ret != 0) continue;
    
    fp = popen("/tmp/.expr", "r");
    assert(fp != NULL);

    int result;
    fscanf(fp, "%d", &result);
    pclose(fp);
    // print auto-gene expr and its result
    printf("%u %s\n", result, buf);
    // reset buf for next gen_rand_expr()
    reset_buf();
  }
  return 0;
}

The code works well in most cases,but sometimes it will occur div0 problem and write illegal expr to test file,like below

./gen-expr 20
(normal case...)
/tmp/.code.c: In function ‘main’:
/tmp/.code.c:2:53: warning: division by zero [-Wdiv-by-zero]
    2 | int main() {   unsigned result =  (( 121/  (((  105 / ( 22 / 42  )/105  ) ))+74  +81 ) /118  ) +20 ;   printf("%u", result);   return 0; }

Is there any way to avoid this situation ? BTW, I don't wanna resovle the expression string to see if there is ‘/ (0)’ in buf. Thx for you great help.

c


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source