0

In the function below, I have a commented printf. When I uncomment it, the function works perfectly fine, when it remains commented, the function seems to access random memory or randomly cuts off at the 8th character, seemingly erratically. Why does this printf situation save the function? Other fixes or debug attempts I have tried have failed.

char* temp(char* file, int max) {
    //First read the file and get info
    FILE *r = fopen(file, "r");
    
    char text[max];
    char ch;
    int i = 0;

    while ((ch = fgetc(r)) != EOF){
        text[i] = ch;
        i++;
    }
    //printf("%d",i);
    text[i] = '\0';
    //close up
    fclose(r);

    char *rt = text;
    return rt;
}

Suggestions?

Seren541
  • 59
  • 3
  • 1
    what's `max`? What value does `i` end up with? You also can't return `text` (or a pointer to it), it goes out of scope and dies when the function returns. You'll need to use [`malloc`](https://linux.die.net/man/3/malloc) or similar for memory allocation to persist outside of the function. – yano Jan 06 '22 at 22:17
  • 4
    `rt` is a pointer to a *local* array. You can't return it from the function and use it's value outside. Your program has an undefined behavior, that is why unrelated things change the observed behavior. – Eugene Sh. Jan 06 '22 at 22:17
  • Max is set to 1000, i ends up at 67. I will try to use malloc. – Seren541 Jan 06 '22 at 22:19
  • you're staying in bounds then. Assuming the file opens correctly (you should check `r != NULL` to be sure), only problem I see is returning the local array. – yano Jan 06 '22 at 22:22
  • There is no reason to do `char *rt = text; return rt;`. You can just write `return text;` It's still wrong, though, since you can't return the address of a local variable. – William Pursell Jan 06 '22 at 22:23
  • @WilliamPursell I see it a lot actually. For some reason people believe that assigning it to a pointer and then returning the pointer will somehow make it legal to be returned. – Eugene Sh. Jan 06 '22 at 22:25
  • 3
    the variable `ch` needs to be of type `int` and not `char`. – Pablo Jan 06 '22 at 23:02

0 Answers0