在使用free(someUnrelatedPointer)之前,C静态主返回值为0?

时间:2012-12-11 10:26:33

标签: c windows gcc mingw

我正在学习C而且我做了这个(下面的代码我无法理解为什么我得到类似-1073740940的程序返回值,应该是0

#include <stdio.h>
#include <stdlib.h> //For using malloc;


struct Vertex{
    int x;
    int y;
    int z;
};

int main(){
    int ret = 0;
    struct Vertex myVertex;
    struct Vertex *myVertexPtr = malloc(sizeof(*myVertexPtr));


    myVertexPtr = &myVertex;

    myVertex.x = 1;
    myVertex.y = 2;
    myVertex.z = 3;

    printf("%d\n", myVertexPtr->x);
    printf("%d\n", myVertexPtr->y);
    printf("%d\n", myVertexPtr->z);

    getchar();

    free(myVertexPtr); //When this line is included I get the strange program return    value (And, "This program has stopped working properly windows error")
                   //When this line is not included it returns fine, but I'm under the impression it is good practice to free pointers

    return 0;
}

我正在使用MinGW GCC编译

3 个答案:

答案 0 :(得分:1)

这一行:

myVertexPtr = &myVertex;

覆盖malloc()返回的指针,以便将错误的值传递给导致错误的free()。它还会导致内存泄漏,这在更长时间运行的程序中会出现问题。不要这样做!

它应该被删除,如果你想在堆上使用顶点,那就这样做:

myVertexPtr = malloc(sizeof *myVertexPtr);
myVertexPtr->x = 1;
myVertexPtr->y = 2;
myVertexPtr->z = 3;

如果您想要一个指向堆栈顶点的单独指针,请删除malloc()

myVertexPtr = &myVertex;

答案 1 :(得分:0)

myVertexPtr = &myVertex;

这将为myVertexPtr分配myVertex的地址,该地址位于堆栈上。你想在以后免费试用。 我很惊讶,你没有得到一个段错误。

应该只为malloc / calloc返回的地址调用

free。您的代码将导致未定义的行为。

答案 2 :(得分:0)

myVertexPtr =&amp; myVertex;

如上所示,如果你想为myVertexPtr和myVertex共享公共内存,你需要使用motoc。

现在你的问题是当你添加free()语句时你会得到奇怪的返回值。那是因为通过分配myVertexPtr =&amp; myVertex来改变myVertexPtr的内存指针;

所以当你添加free()语句时,它会尝试释放不是来自堆的内存,这就是为什么你得到奇怪的返回值。

删除malloc和free语句,你的程序应该可以正常工作。希望它有所帮助......