我正在查看的一些代码声明并稍后初始化指向结构的指针.
mcsConsole_t *mcsConsole;
mcsConsole = (mcsConsole_t *) malloc(sizeof (mcsConsole_t) );
Run Code Online (Sandbox Code Playgroud)
这个结构的typedef是:
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;
Run Code Online (Sandbox Code Playgroud)
释放此内存时,指针名称前面会包含一个&符号.
free(&mcsConsole);
Run Code Online (Sandbox Code Playgroud)
这个的目的是什么,你什么时候使用&符号来免费通话?我习惯于通过简单地提供指针变量名来查看释放内存的代码.
int *ptr = malloc( sizeof(*ptr) );
free(ptr);
Run Code Online (Sandbox Code Playgroud)
这是程序中的一个错误.
指向的对象mcsConsole如果在文件范围声明,则具有静态存储持续时间,如果在块范围声明,则具有自动存储持续时间.您只能释放具有已分配存储持续时间的对象.
如果您free(&p)在程序中看到并且p不是宏,则可能是错误.