0

I am trying to use fprintf() to display output to another terminal in C.

On checking the issue with multiple printf statement, something unexpected result is showing and I have no clue what is the cause of the problem and how to fix it.

If you run the code with input "Banana", the outputs: Output1, Output2, Output3, Output4 and Output7 are correctly displayed. But outputs Output5 and Output6 are not.

Can someone explain what is the cause of the problem on Output5 and Output6?

#include <stdio.h>
#include <stdlib.h>     // EXIT_FAILURE

#define SIZE 100    // maximum characters allowed in the chat

void displayChild(const char *string){
    fprintf(stdout, "Output4: %s", string);
    int exit_status = system("gnome-terminal");
    FILE *fp;
    fp = fopen("/dev/pts/1", "w");
    fprintf(fp, "Output5: %s\n", string);
    fprintf(stdout, "Output6: %s\n", string);
    fprintf(fp, "Output7: %s\n", "Apple");
    fclose(fp);
}

const char *readChild(){
    char string[SIZE] = "\0";
    fgets(string, SIZE, stdin);
    char *returnString = string;
    fprintf(stdout, "Output1: %s\n", string);
    fprintf(stdout, "Output2: %s\n", returnString);
    return returnString;
}


int main(){

    const char *string;
    string = readChild();
    fprintf(stdout, "Output3: %s\n", string);
    displayChild(string);

    return 0;
}
Joy
  • 47
  • 6
  • 2
    In `readChild` you are returning `returnString` which has been initialized to the local array `string`. So you are effectively accessing `string` *after* it has gone out of scope -- that's undefined behaviour. – G.M. Apr 07 '23 at 17:38
  • Ahh. So, stupid of me. Changed to "static" fixed the problem. Thank you so much. – Joy Apr 07 '23 at 17:44
  • Other option, declare `char string[SIZE] = "";` in `main()` and pass it as a parameter to your function, e.g. `char *readChild (char *string) { ... }` – David C. Rankin Apr 07 '23 at 17:57

0 Answers0