标签:
在复制字符串的时候,出现如下难以理解之处:
测试程序的目的是定义一个指针指向字符串常量,并且将这个字符串常量复制到另一个经过内存分配的字符串指针。
正常理解范围(1):
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(void)
{
char* p1 = "abcdefg";
char* p2 = (char*)malloc(sizeof(p1));//pass
strcpy(p2,p1);
printf("%s",p2);
return 0;
}正常理解范围(2):#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(void)
{
char* p1 = "abcdefg";
char* p2 = (char*)malloc(sizeof(char)*strlen(p1)+sizeof('\0'));//pass
strcpy(p2,p1);
printf("%s",p2);
return 0;
}本应该出错的程序:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(void)
{
char* p1 = "abcdefg";
char* p2 = (char*)malloc(sizeof(char)*strlen(p1));//pass
strcpy(p2,p1);
printf("%s",p2);
return 0;
}由于p1字符串常量的内存大小还包括一个 ‘\0‘
字符。所以分配内存的时候缺少了一个字节。本应该报错。但是在Code::Blocks(GCC) Visual C++ 6.0中测试,均无异常情况。
再做一个测试:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(void)
{
char* p1 = "abcdefg";
char* p2 = (char*)malloc(sizeof(char));//pass
strcpy(p2,p1);
printf("%s",p2);
return 0;
}
我决定再做一个测试:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(void)
{
char* p1 = "abcdefg";
char* p2 = (char*)malloc(0);//pass
strcpy(p2,p1);
printf("%s",p2);
return 0;
}
目前为止,不知道原因。待续。
C Language Study - 内存分配的一个奇异之处
标签:
原文地址:http://blog.csdn.net/oimchuan/article/details/44039007