Malloc and free. C programming tips

In C programming, we usually have to define a lot of customized structs, they work similar to classes but without the methods.

Usually to construct a struct, we have the following

struct xyz {
int a;
int b;

Then when you use it, you have to do

struct xyz * apointer= malloc(sizeof(struct xyz));

To simplify the code, we use

typedef struct xyz * xyz

This way, we don't have to type "struct xyz *" every time, but simply use a "xyz".

Problem usually happen when you try to free the memory. After you are done with this struct.
Then you free the memory that "apointer" points to by using free(apointer)

Many times people will get a "invalid size", or "invalid address" error when they try to free the memory and get very confused. I found it very often that this happens very often with one case. So I point it out to remind myself.
xyz curPointer=malloc(sizeof(xyz));

This means you are only malloc enough space for a xyz pointer!, which is only 8 byte( or 4 byte). You should use
xyz curPointer=malloc(sizeof(struct xyz));

This is very important!
If you did not "malloc" enough space for one struct and write more bytes into the space. You'll overwrite the memory space adjacent to it. (C does not check for this when it writes to this location exceed the malloc space). When you try to free the next memory block, it will not understand what to free, because this block was overwritten.

Suppose you have block A and B adjacent to each other. A is 8 byte, B is also 8 byte.

Then you write 9 bytes to A, and then try to free B. You'll get the error I was talking about.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>