Returning "string" (or character array?) from a function / malloc() question.
I am trying to figure out a good way (as in good practices I suppose) to return "string" information from a function. And by string, I think I probably mean a character array. After a bit of searching around, I have something that appears to work, but I'm not sure if it's written well. And more importantly, I'm not sure if I'm freeing memory when I'm done with the call.
In my demo code below (which compiles and works), I'm sending an integer to a function, and based on the value of that integer, I'm returning a string? character array? pointer?
I got this working using malloc, which is brand new to me. For as long as I've tinkered with C, I've heard of malloc many times, but have never used it myself. So this is unfamiliar territory.
I believe I need to use free() after using malloc(), but I'm not sure where to use it.
So my questions are:
1. despite the fact that this works (for me), is it obviously bad code or broken in some way?
2. Do I need to use free(). If so, where do I use it? I tried using free(diceDamage) in main() just before return 0, but that doesn't work. And it doesn't seem logical to use free() at the end of the getDamage() function because that seems like it would free() the memory before it got a chance to be used.
Code:
#include <stdio.h>
#include <stdlib.h> // needed by malloc()
char *getDamage(int level) {
// Allocate memory for 9 characters + 1 more character
// for the string terminator \0
char *diceDamage = malloc((9 + 1) * sizeof(char));
if (diceDamage == NULL) {
return NULL;
}
if (level > 1 && level <= 3) {
diceDamage = "dice(1,4)";
} else if (level > 3 && level <= 5) {
diceDamage = "dice(1,5)";
} else {
diceDamage = "dice(2,7)";
}
return diceDamage;
}
int main(void) {
int baseDamage = 4; // Example of base damage
int playerLevel = 3; // Example of player's level
char *diceDamage = getDamage(playerLevel);
printf("Total damage: %d + %s\n", baseDamage,diceDamage);
return 0;
}