可以说我在程序中动态创建了一个字符串
char* s = malloc(sizeof(char) * 128);
Run Code Online (Sandbox Code Playgroud)
在我们开始使用s之前,如何检查内存是否已分配?
free(s);
Run Code Online (Sandbox Code Playgroud)
在使用free()之前,我想检查是否有其他指针指向s.
malloc() 返回指向新分配的内存的指针或NULL.
所以检查NULL
char *s = malloc(128); /* sizeof (char), by definition, is 1 */
if (s == NULL) {
/* no memory allocated */
} else {
/* use memory */
free(s);
}
Run Code Online (Sandbox Code Playgroud)
s只有当你(程序员)创建它们时,还有其他指针指向哪里的点.