I am working on a method in C where I am trying to convert a decimal to its base. I am having trouble with returning a Char*. I still am unsure how to return a pointer. When I compile this code, I get a warning saying
"warning: function returns address of local variable [-Wreturn-local-addr]". and it has to do with my res character. I am uncertain with why I cannot return res, if it's a char. I don't understand what I am suppose to return if I can't return res. Please help.
//return res;
char reVal(int num)
{
if (num >= 0 && num <= 9)
return (char)(num + '0');
else if(num = 10)
{
return (char)(num - 10 + 'A');
}
else if(num = 11)
{
return (char)(num - 11 + 'B');
}
else if(num = 12)
{
return (char)(num - 12 + 'C');
}
else if(num = 13)
{
return (char)(num - 13 + 'D');
}
else if(num = 14)
{
return (char)(num - 14 + 'E');
}
else if(num = 15)
{
return (char)(num - 15 + 'F');
}
}
// Utility function to reverse a string
void strev(char *str)
{
int len = strlen(str);
int i;
for (i = 0; i < len/2; i++)
{
char temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
char* decToBase(int base, int dec)
{
int index = 0; // Initialize index of result
char res[100]; // Convert input number is given base by repeatedly
// dividing it by base and taking remainder
while (dec > 0)
{
res[index++] = reVal(dec % base);
dec /= base;
}
res[index] = '\0';
// Reverse the result
strev(res);
return res;
int main()
{
char* base = decToBase(16, 248);
}
Regardless, the outcome I want is to have the method return "f8" as the outcome.
In your decToBase()
function, the issue it's warning about is the use of char res[500];
, which is an array that's allocated on the stack as a local variable. These are all thrown away when the function returns, so if you return a pointer to (or: the address of) the res
array, this pointer points to junk on the stack.
You have to find some other way to manage this allocation, and though some might suggest using malloc()
to allocate memory from the system, this is probably a bad idea because it's asking for problems with memory leaks.
Better is to pass in the buffer you want it to fill, and use that. Then the caller does the allocation and you don't worry about memory leaks.
char *decToBase(int base, int dec, char *outbuf)
{
int index = 0; // Initialize index of result
// Convert input number is given base by repeatedly
// dividing it by base and taking remainder
while (dec > 0)
{
outbuf[index++] = reVal(dec % base);
dec /= base;
}
outbuf[index] = '\0';
// Reverse the result
strev(outbuf);
return outbuf;
}
and then your main
function would look like:
int main()
{
char decbuf[500];
decToBase(16, 248, decbuf);
printf("Buffer is %s\n", decbuf);
}
This is still not super ideal, because your decToBase()
function doesn't know how big outbuf
is, and overflows are possible, so the experience and/or paranoid programmer will also pass in the size of outbuf so your function knows how much to use.
But that's a step you'll get to later.