69,373
社区成员
发帖
与我相关
我的任务
分享
C:\Documents and Settings\Administrator>cat f.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char * s = (char *)malloc(100);
s = "Hello world!";
puts(s);
printf("%02X\n",s);
free(s);
puts(s);
printf("%02X\n",s);
if(s == NULL)
printf("Hello\n");
else
printf("no\n");
return 0;
}
C:\Documents and Settings\Administrator>g++ f.c -o f && f
f.c: 在函数‘int main()’中:
f.c:8:13: 警告:不建议使用从字符串常量到‘char*’的转换 [-Wwrite-strings]
Hello world!
403064
Hello world!
403064
no
C:\Documents and Settings\Administrator>g++ -v
使用内建 specs。
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=d:/mingw/bin/../libexec/gcc/mingw32/4.6.2/lto-wrapper.exe
目标:mingw32
配置为:../gcc-4.6.2/configure --enable-languages=c,c++,ada,fortran,objc,obj-c++
--disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgomp --disa
ble-win32-registry --enable-libstdcxx-debug --enable-version-specific-runtime-li
bs --build=mingw32 --prefix=/mingw
线程模型:win32
gcc 版本 4.6.2 (GCC)
s = "Hello world!";
int main ()
{
char * s = (char *)malloc(100);
s = "Hello world!"; //s指向一个字符串常量
free(s); //试图free字符串常量, 会Segmentation fault, 程序终止
if(s == NULL)
printf("Hello\n");
else
printf("no\n");
return 0;
}
假如程序是这样的:
char * s = (char *)malloc(100);
free(s); //free掉s指向的内存空间,但是s并不等于NULL, s还是会指向原来的内存地址,只是那块内存已经free掉了
if(s == NULL)
printf("Hello\n");
else
printf("no\n"); //最后会输出no
return 0;
一个比较好的习惯就是每次free(s)后,将s = NULL;