在C中重用内存

时间:2015-08-26 06:21:06

标签: c pointers memory

我在使用和理解C中的free()函数时遇到了麻烦。

我尝试编写这个示例以继续重用指针,但我不明白为什么会出现错误:

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


typedef struct box
{
    char message[20];
}box;


box *newBox()
{
    box *inBox;
    inBox = (box *) malloc(sizeof(box));

    return inBox;
}


int main()
{
    box *temp = NULL;


    temp = newBox();
    strcpy(temp->message,  "Hello");
    printf("%s\n", temp->message);

    free(temp);

    strcpy(temp->message,  "World");
    printf("%s\n", temp->message);

    free(temp);

    strcpy(temp->message,  "People");
    printf("%s\n", temp->message);

    return 0;   

}

输出结果为:

Hello
World
memory(531,0x7fff77e9e300) malloc: *** error for object 0x7fe8ba404a90: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

有解决方法吗?

3 个答案:

答案 0 :(得分:6)

我不确定你为什么在这里有两个'numpy.ndarray' object has no attribute 'get_figure'

free(temp)

该代码应为

temp = newBox();
strcpy(temp->message,  "Hello");
printf("%s\n", temp->message);

free(temp); /* ? */

strcpy(temp->message,  "World");
printf("%s\n", temp->message);

free(temp); /* ? */

strcpy(temp->message,  "People");
printf("%s\n", temp->message);

一旦你temp = newBox(); strcpy(temp->message, "Hello"); printf("%s\n", temp->message); strcpy(temp->message, "World"); printf("%s\n", temp->message); strcpy(temp->message, "People"); printf("%s\n", temp->message); free(temp); /* Free the allocated memory after use */ 记忆,你就不能使用它。所以free最后的记忆。

旁注:演员阵容:

free

不是必需的,here is why

答案 1 :(得分:3)

inBox = (box *) malloc(sizeof(box));

执行此操作后,将释放free(temp); (在本例中)分配的内存。

因此分配的内存已经消失,无法再次使用,如果需要,您必须再次分配内存。

只有在分配的内存上执行所需的操作后,才能使用malloc()内存。

答案 2 :(得分:2)

一旦你释放了通过malloc获得的内存,它就不再属于你了,使用它是未定义的行为。

每个malloc必须有一个空闲,并且必须在新malloc中使用它之前释放指针 - 但除非你做一个测试或分配不同的内存大小(并且在那里),这没有多大意义最后一个用例,你最好使用realloc

假设你有充分的理由多次使用malloc / free(这段代码表现出这样的要求),你可以这样做:

int main()
{
    box *temp = NULL;


    temp = newBox();
    strcpy(temp->message,  "Hello");
    printf("%s\n", temp->message);

    free(temp);

    temp = newBox();
    strcpy(temp->message,  "World");
    printf("%s\n", temp->message);

    free(temp);

    temp = newBox();
    strcpy(temp->message,  "People");
    printf("%s\n", temp->message);
    free(temp);

    return 0;   

}

请不要在C中投射malloc结果!它应该是:

box *newBox()
{
    box *inBox;
    inBox = malloc(sizeof(box));

    return inBox;
}