I've been working on some practice problems for school, and in one of them, an inputted integer has to be written to a dynamically allocated string. The code does it's job fine until it gets to freeing the allocated memory, where heap corruption strikes.
Can someone please explain why it's happening and what I'm doing wrong?
int main() {
char *string = NULL;
char **string2 = &string;
Conversion(string2);
printf("Entered number converted to string: %s", string);
free(string);
return 0;
}
int Conversion(char **string) {
int num = 0, temp = 0, dcount = 0;
printf("Enter number: ");
scanf(" %d", &num);
temp = num;
while (temp != 0) {
temp /= 10;
dcount++;
}
*string = (char*)malloc(dcount*sizeof(char));
if (*string == NULL) {
printf("Error during memory allocation!");
return -1;
}
sprintf(*string, "%d", num);
return 0;
}