I am learning C and I did this (code below and I cannot understand why I am getting program return value of something like -1073740940 when it should be 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;
}
I am using MinGW GCC to compile
This line:
overwrites the pointer returned by
malloc(), so that you pass the wrong value tofree()which causes the error. It also causes a memory leak, which would be a problem in a more long-running program. Don’t do this!It should simply be removed, if you want to work with a vertex on the heap, do that:
If you want to have a separate pointer to a vertex on the stack, drop the
malloc():