Using ampersand (&) in free () call
Some code I'm looking at declares and then initializes a pointer to a struct.
mcsConsole_t *mcsConsole;
mcsConsole = (mcsConsole_t *) malloc(sizeof (mcsConsole_t) );
The typedef for this structure 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 the ampersand to call to release? I'm used to seeing code where memory is freed just by specifying the name of the pointer variable.
int *ptr = malloc( sizeof(*ptr) );
free(ptr);
source to share
This is a bug in the program.
The object pointed to by the object has mcsConsole
that has either a static storage duration if declared in file scope or automatic storage time if declared in block scope. You can free an object with an allocated storage duration.
If you see it free(&p)
in the program and p
not a macro, this is probably a bug.
source to share
This ampersand receives an address mcsConsole
, which itself is a pointer to a structure mcsConsole_t
. I cannot imagine a single scenario where this call free
would be valid. The system will try a free
pointer that is on the stack (or possibly static) as if it were a heap-allocated structure. It smells like a bug, and especially bad at that.
source to share