我正在学习 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 编译
这一行:
myVertexPtr = &myVertex;
覆盖 malloc()
返回的指针,因此您将错误的值传递给 free()
,从而导致错误。它还会导致内存泄漏,这在运行时间更长的程序中将是一个问题。不要这样做!
它应该简单地被删除,如果你想在堆上使用一个顶点,这样做:
myVertexPtr = malloc(sizeof *myVertexPtr);
myVertexPtr->x = 1;
myVertexPtr->y = 2;
myVertexPtr->z = 3;
如果你想有一个单独的指针指向堆栈上的顶点,删除 malloc()
:
myVertexPtr = &myVertex;
我是一名优秀的程序员,十分优秀!