kyle
kyle

Reputation: 129

C static main return value of 0 changing after using free(someUnrelatedPointer) before it?

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

Upvotes: 1

Views: 104

Answers (3)

Kinjal Patel
Kinjal Patel

Reputation: 405

myVertexPtr = &myVertex;

as shows above, if you want to share common memory for both myVertexPtr and myVertex, you need mot use malloc.

now your problem is when you add the free() statement you get strange return value. that is because have changes the memory pointer for myVertexPtr by assigning myVertexPtr = &myVertex;

so when you add free() statement, it will try to free the memory which is not from heap thats why you are getting strange return value.

remove the malloc and free statement, your program should work fine. hope it helps.....

Upvotes: 0

anishsane
anishsane

Reputation: 20980

myVertexPtr = &myVertex;

This will assign myVertexPtr with address of myVertex, which is on stack. Which you are trying to free later on. I am surprised, that you did not get a seg-fault.

free should be called only for addresses returned by malloc/calloc. Your code will result in undefined behaviour.

Upvotes: 0

unwind
unwind

Reputation: 400159

This line:

myVertexPtr = &myVertex;

overwrites the pointer returned by malloc(), so that you pass the wrong value to free() 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:

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

If you want to have a separate pointer to a vertex on the stack, drop the malloc():

myVertexPtr = &myVertex;

Upvotes: 2

Related Questions