I am writing a function to convert a number of any base up to 16 to a string. Here's what I have so far:
The only problem is (well let's not say only since I haven't finished testing the rest of the code...) that when I use malloc within a function then the memory gets freed once the function exits, or at least that's what I think is happening. In case you are wondering, yes I'm aware of the consequences of not following this up with a call to free() later on if this wasn't the case . Anyway, I could put the code to determine the how many digits a number takes in a seporate function and allocate the memory within the scope it will be used in, but I think this method makes for neater code so I'd like to get it working if possible. All I need is a function that allocates memory in a way so that it will not get deallocated unless I explicitly say it should be. Anyone know of one? I'm writing this code for a windows based program if it makes a difference. Also, if you happen to notice any other bugs in this feel free to point them out .Code:char * IntToString(int number, int base) { int i = 0; char * charArray; int digits; // Base 16 is the maximum I decided to allow, but even "as is" this function could support higher numbers if(base < 2 || base > 16) return (char *) 0; //Determine the memory required to hold the string while(number) { number /= base; i++; } //Save i as the total digits the number will take digits = i; //Allocate memory for the string if(!(charArray = (char *) malloc(i + 1))) return (char *) 0; //Put each digit of the number in it's own array position for(i; i >= 0; i--) { charArray[i] = number % base; number /= base; if(!(number)) break; } //Now convert the digits to their correct ASCII values for(i = 0; i <= digits; i++) { if(charArray[i] < 10) charArray[i] += 48; else charArray[i] += 55; } //Terminate the string charArray[digits + 1] = '\0'; return charArray; }
Mod edit: changed php tags to code tags