free函数怎么正确使用,求大神解答。

free函数如何正确使用,求大神解答。。
这是我做的ACM的一道题,有个地方实在想不明白错在哪。。求大神帮看看
先上题:

It was said that when testing the first computer designed by von Neumann, people gave the following problem to both the legendary professor and the new computer: If the 4th digit of 2^n is 7, what is the smallest n? The machine and von Neumann began computing at the same moment, and von Neumann gave the answer first.

Now you are challenged with a similar but more complicated problem: If the K-th digit of M^n is 7, what is the smallest n?

Input

Each case is given in a line with 2 numbers: K and M (< 1,000).

Output

For each test case, please output in a line the smallest n.

You can assume:

The answer always exist.
The answer is no more than 100.
Sample Input

3 2
4 2
4 3
Sample Output

15
21
11

题目很简单,但用到大数乘法,以下是我的代码


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void reverse(char *s)
{
    int len = strlen(s);
    int i, j;
    char c;
    for (i = 0, j = len - 1; i < j; i++, j--)
    {
        c = *(s + i);
        *(s + i) = *(s + j);
        *(s + j) = c;
    }
}

char *appendTailZero(char *s, int zeros)
{
    int i, len = strlen(s);
    char *r = malloc(len + zeros + 1);
    for (i = 0; i < len; i++)
        *(r + i) = *(s + i);
    for (i = len; i < len + zeros; i++)
        *(r + i) = '0';
    *(r + len + zeros) = '\0';
    return r;
}

char *add(char *s1, char *s2)
{
    int l1 = strlen(s1);
    int l2 = strlen(s2);
    int len = l1 > l2 ? l1 : l2;
    char *r = malloc(len + 2);
    int i, prev = 0, a, b, sum;
    for (i = 0; i < len; i++)
    {
        a = l1 - 1 - i >= 0 ? *(s1 + l1 - 1 - i) - '0' : 0;
        b = l2 - 1 - i >= 0 ? *(s2 + l2 - 1 - i) - '0' : 0;
        sum = a + b + prev;
        *(r + i) = sum > 9 ? sum - 10 + '0' : sum + '0';
        prev = sum > 9 ? 1 : 0;
    }
    if (prev)
    {
        *(r + len) = '1';
        *(r + len + 1) = '\0';
    }
    else
        *(r + len) = '\0';
    reverse(r);
    return r;
}

char *multiplyHelper(char *s1, int digit)
{
    int i, res, prev = 0, len = strlen(s1);
    char *r = malloc(len + 2);
    if (!digit)
    {
        *r = '0';
        *(r + 1) = '\0';
        return r;
    }

    for (i = 0; i < len; i++)
    {
        res = (*(s1 + len - 1 - i) - '0') * digit + prev;