Can't free a Malloc'd string

2019-08-11 23:57发布

This one should be quick, I think.

EDIT: This is for my CS113 class. I just needed to free all the memory. If Valgrind found any memory leaks, I'd lose points. :P

Regardless, I figured out that it apparently just required me to free stuff in Main that related to the return value of zero_pad. Once I did so, it worked fine. I'd mark this post as "complete" if I knew how.

char *zero_pad(struct cpu_t *cpu, char *string)
{
    char *zero_string = malloc(cpu->word_size + 1); 
    int num_zeros = ((cpu->word_size) - strlen(string));
    int i;

    for(i = 0; i < num_zeros; i++)
    {
        zero_string[i] = '0';
    }

    return strncat(zero_string, string, strlen(string));    
}

I need to free zero_string, since I allocated it. However, I have no idea how. If I free it before I return, then I've lost that data and can't return it. If I try to free it after, the function has already returned and thus can't go on to freeing it.

I tried to use strcpy to copy the string in zero_string into a new string, but I must have been doing it wrong, because I just ended up with a massive mess.

So, what do you all think?

标签: c string malloc
1条回答
Melony?
2楼-- · 2019-08-12 00:49

What is cpu->word_size ? Are you sure that cpu->word_size >= strlen(string) in any case ?

Anyway, the returned buffer is mallocated so it is the caller's responsibility to free it. Another possibility is to use a static variable if you know the maximum size needed. This is the code.

#define MAX_SIZE 128 /* adjust this */
char *zero_pad(struct cpu_t *cpu, char *string)
{
    static char zero_string[MAX_SIZE]; 
    int num_zeros = ((cpu->word_size) - strlen(string));
    int i;

    for(i = 0; i < num_zeros; i++)
    {
        zero_string[i] = '0';
    }

    strcpy(zero_string + i, string); 
    return zero_string;   
}

Obviously, the caller should be informed that the returned buffer is always the same (the caller has to duplicate the returned buffer if needed, e.g. using strdup() and later free()).

查看更多
登录 后发表回答