I have some C code that is supposed to call a function and return a string. Somewhere I read this is difficult due to memory allocation not being constant or something? Anyway, I was told I should rather return the pointer to the string. However, I can't explain why printf sometimes produces gibberish, and sometimes not:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * execTasks() {
int d, m, y;
char str[6] = {};
d = 10; m = 5; y = 18;
memset(&str, 0, sizeof(str));
sprintf(str, "%02d%02d%02d", d, m, y);
printf("Works fine: %s\n", str); // Works fine even with additions
char *s_ptr = str;
return s_ptr;
}
int main() {
char * str;
str = execTasks();
printf("%s", str); // works fine!
printf("%s\n", str); // produces gibberish!
printf("%s,%s", str, str); // also gibberish!
return 0;
}
Can somebody explain to me why printf("%s", str);
works fine, while printf("%s\n", str);
and variations print out gibberish?
Or am I doing something wrong with returning the pointer? Essentially the function should return a date as string in the format DDMMYY. I need this string later in the main function to append it to another string.