Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an ampersand (&) in a call to free()

Tags:

c

pointers

free

Some code I'm looking at declares and later initializes a pointer to a struct.

mcsConsole_t *mcsConsole;
mcsConsole = (mcsConsole_t *) malloc(sizeof (mcsConsole_t) );

The typedef for this struct is:

typedef struct {
    unsigned int   reqType;             /* Request Type                */
    unsigned int   consoleID;           /* Console ID                  */
    int            returnCode;          /* Return code                 */
    int            reasonCode;          /* Reason code                 */
    unsigned int   ecbArea;             /* ECB posted for responses    */
    char           reserved[4];         /* Available                   */
    cmdRequest_t  *cmdRequest;          /* Pointer to command request  */
    cmdResponse_t *cmdResponse;         /* Pointer to command response */
} mcsConsole_t;

When this memory is freed, an ampersand is included in front of the pointer name.

free(&mcsConsole);

What is the purpose of this, and when do you use an ampersand with a call to free? I'm used to seeing code where memory is freed by simply supplying the pointer variable name.

int *ptr = malloc( sizeof(*ptr) );
free(ptr);
like image 600
Alex Parker Avatar asked Nov 17 '25 18:11

Alex Parker


2 Answers

It's a bug in the program.

The object pointed at is mcsConsole which has either static storage duration if declared at file scope or automatic storage duration if declared at block scope. You can only free an object with allocated storage duration.

If you see free(&p) in a program and p is not a macro, it is probably a bug.

like image 124
ouah Avatar answered Nov 20 '25 08:11

ouah


That ampersand is getting the address of mcsConsole, which is itself a pointer to a mcsConsole_t structure. I can't think of a single scenario where that call to free would be valid. The system will attempt to free the pointer, which is on the stack (or possibly static), as though it were a structure allocated on the heap. This smells like a bug, and a particularly bad one at that.

like image 26
acwaters Avatar answered Nov 20 '25 08:11

acwaters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!