1

I was wondering If someone could let me know the best way to return a sprintf string.

So (I think) I understand why this isn't working at all, it's because once the function is run everything on the stack is destroyed so buffer is returning noting.

I have a couple of similar functions like the one below and I'm out of ideas on how I should go about returning the sprintf string. Should I malloc the buffer for every function?

const char* gradeCheck(double mark) {
    char buffer [100];
    if (mark > MAX_MARK || mark < MIN_MARK) {
        sprintf(buffer, "INVALID TYPE\n");
        return buffer;
    } else if (mark >= PASSING_MARK && mark <= MAX_MARK) {
        sprintf(buffer, "Student achieved %.2lf\n", mark);
        return buffer;
    } else {
        sprintf(buffer, "Student achieved %.2lf which means they failed ;(\n", mark);
        return buffer;
    }
}
lajuc
  • 9
  • 2
  • 1
    `char buffer [100];` is declared local to `gradeCheck` and its memory is no longer valid after the function returns. Allocate `buffer`, e.g. `char *buffer = malloc (100 +1);` (and don't forget to validate the allocation succeeds -- or pass `buffer` as a parameter to the function) – David C. Rankin Feb 03 '19 at 05:10
  • @DavidC.Rankin Thank you sir for the explanation, got it working. Have a great day! – lajuc Feb 03 '19 at 05:19
  • 1
    (don't forget to `free` the memory you allocate when it is no longer needed `:)` – David C. Rankin Feb 03 '19 at 05:21

1 Answers1

0

The way you are attempting right now is not going to work since buffer is on the stack for that function and no longer exists once the function returns.

If you want to return an array from a function, you can either declare it to be static, so it goes in the process’ data section rather than on the stack, or allocate it with malloc(100), and later free it in the calling code when you’re done with it.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85