点击(此处)折叠或打开
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
void create_mem()
-
{
-
char *s;
-
s = (char *)malloc(sizeof(char)*65535);
-
snprintf(s,65535,"%s","aaaaaaaaaaaaaaa");
-
free(s);
-
s=NULL;
-
}
-
-
int main ( void )
-
{
-
int i = 0;
-
-
for ( i = 0 ; i <1000000 ; i++ )
-
{
-
printf("== %d ==\n",i);
-
create_mem();
-
}
-
return 0;
- }
第二段代码:
点击(此处)折叠或打开
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
void create_mem()
-
{
-
char *s;
-
s = (char *)malloc(sizeof(char)*65535);
-
snprintf(s,65535,"%s","aaaaaaaaaaaaaaa");
-
// free(s);
-
// s=NULL;
-
}
-
-
int main ( void )
-
{
-
int i = 0;
-
-
for ( i = 0 ; i <1000000 ; i++ )
-
{
-
printf("== %d ==\n",i);
-
create_mem();
-
}
-
return 0;
- }
第三段代码:
点击(此处)折叠或打开
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
void create_mem()
-
{
-
char *s;
-
s = (char *)malloc(sizeof(char)*65535);
-
//snprintf(s,65535,"%s","aaaaaaaaaaaaaaa");
-
// free(s);
-
// s=NULL;
-
}
-
-
int main ( void )
-
{
-
int i = 0;
-
-
for ( i = 0 ; i <1000000 ; i++ )
-
{
-
printf("== %d ==\n",i);
-
create_mem();
-
}
-
return 0;
- }
结论:
1、使用 malloc 分配内存后,一定要使用 if ( s == NULL ) 来进行判断。
2、malloc 分配内存失败,不会引起程序的崩溃,但是如果不检查 malloc 函数分配内存的情况就直接使用,则很有可能会出现针对未知内存区域进行操作的情况,从而导致程序 coredump。
3、要建立良好的习惯,一旦某个被分配的内存不在需要使用的时候,一定要用 free 来释放这块内存,并且将 s 指向 NULL ,以避免不可预知的情况发生。