无法释放malloc分配的字符串 [英] Can't free a Malloc'd string

查看:188
本文介绍了无法释放malloc分配的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是快速的,我想。

This one should be quick, I think.

编辑:这是我的CS113类。我只是需要释放所有内存。如果Valgrind的发现有内存泄漏,我会失分。 :P

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

不管怎样,我想通了,它显然只是要求我在主免费的东西,涉及到zero_pad的返回值。有一次,我这样做了,它工作得很好。我想纪念这个岗位作为完整的,如果我知道怎么样。

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));    
}

我需要释放zero_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.

我试图用strcpy的字符串复制到zero_string一个新的字符串,但我一定是做错了,因为我刚刚结束了一个巨大的烂摊子。

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?

推荐答案

什么是 CPU-&GT; word_size ?你确定 CPU-&GT; word_size&GT; = strlen的(字符串)在任何情况下?

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

总之,返回缓冲区mallocated所以它是调用者负责释放它。另一种可能性是,如果你知道所需要的最大尺寸为使用静态变量。这是code。

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;   
}

显然,调用者应该被告知返回的缓冲区始终是相同的(调用者必须复制返回的缓冲区,如果需要,可以使用如的strdup()后来免费())。

这篇关于无法释放malloc分配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆