Search code examples
cstructmallocfree

Using free() on struct only clearing first object


I have a struct that is defined as a pointer. Inside, it has 2 double variables. The program keeps messing up after I try to free any of the variables of the struct type. After some print statements, I have found out that only the first object is getting freed. What can I do?

Struct definition (Can't change due to assignment)

struct ctype {
  double real, imag; // real & imaginary parts
};
typedef struct ctype *complex;

Allocating space

complex c;
c = malloc(sizeof(comples));

Current attempt at freeing space

free(c);

Current output after printing real & imag parts after freeing

real: 0.000000 imag: 2.001000

I feel like I have the project pretty well understood, but this problem seems to be breaking everything and preventing me from progressing. Any help would be appreciated. If you need more code, let me know.

Edit: I see that I was misunderstanding what free does. After looking over things though, I am still experiencing crashes whenever I go try to reallocate memory to the pointer c. I will try to explain the project a bit more and give more code. Basically, it is just complex numbers. When the newComplex function is called, it creates the pointer c and allocates space to it, and stores the values for the real and imag parts. It then returns the new complex struct.

The crashing is coming from setting the real or imag part after freeing and then reallocating space.

complex newComplex(double realPart, double imagPart) {
    complex c = NULL;
    c = malloc(sizeof(complex));
 ~set values & returns c~
}
complex c1 = newComplex(2.05,5.02);

~print c1 then free c1~

c1 = newComplex(7.789, 4.567);  <--- Does not execute and crashes

Solution

  • free generally does not clear memory. That is not part of the specification of what it does. free merely updates a database to say the memory is no longer reserved.

    free might alter the memory that has been freed, either because it uses that memory as part of the database, to help track what memory is available, or because debugging features have been turned on, so freed memory is deliberately “scribbled” over so that incorrect attempts to use it as if it still had valid data in it are likely to fail and reveal program bugs. You cannot rely on either of these behaviors without specific documentation for the implementation of the memory allocation routines.

    Additionally, the compiler may know what free does. It is part of the C standard. Because of this, a compiler may treat a pointer to memory that has been freed as an invalid pointer, and attempting to use the pointer might not actually access the memory it used to point to. Using such a pointer does not have behavior defined by the C standard, so the compiler does not have to treat it as a normal variable with a value, and optimization during compilation may produce unexpected effects.