33,311
社区成员
发帖
与我相关
我的任务
分享
//练习代码
#include <stdio.h>
#include <string.h>
#include <malloc.h>
unsigned char a1[] = "hello";
void main(void)
{
int i;
unsigned char *pa2;
pa2 = malloc(strlen(a1) * sizeof(unsigned char));
if(pa2 == NULL)
{
printf("Out Of Memory!");
}
else
{
strcpy(pa2,a1);
for(i=0;i<6;i++)
{
printf("%c",*pa2++);
}
free(pa2);
pa2 = NULL;
}
}
free(pa2);
pa2 = NULL;
//练习代码
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void main(void)
{
int i;
unsigned char a1[] = "hello";
unsigned char *pa2 = NULL;
unsigned char *p = NULL;
pa2 = malloc(strlen(a1) * sizeof(unsigned char));
if(pa2 == NULL)
{
printf("Out Of Memory!");
}
else
{
strcpy(pa2,a1);
p = pa2;
for(i=0;i<6;i++)
{
printf("%c",*p++);
}
free(pa2);
}
}
输出的错误信息:
[/quote]数组越界访问了,malloc了5个字节,因为strlen只是计算了有效字符的个数,而不是数组的实际大小(不包括结束符),所以for循环数组越界访问了
//练习代码
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void main(void)
{
int i;
unsigned char a1[] = "hello";
unsigned char *pa2 = NULL;
unsigned char *p = NULL;
pa2 = (unsigned char*)malloc(sizeof(a1) * sizeof(unsigned char)); //注意看这里,如果使用strlen(a1),则会少分配一个字节
if(pa2 == NULL)
{
printf("Out Of Memory!");
}
else
{
strcpy((char*)pa2,(const char*)a1);
p = pa2;
for(i=0; i<sizeof(a1)-1; i++)
{
printf("%c",*p++);
}
printf("\n");
free(pa2);
pa2 = NULL;
}
}
//练习代码
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void main(void)
{
int i;
unsigned char a1[] = "hello";
unsigned char *pa2 = NULL;
unsigned char *p = NULL;
pa2 = malloc(strlen(a1) * sizeof(unsigned char));
if(pa2 == NULL)
{
printf("Out Of Memory!");
}
else
{
strcpy(pa2,a1);
p = pa2;
for(i=0;i<6;i++)
{
printf("%c",*p++);
}
free(pa2);
}
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
char *pa2 = NULL;
const char a1[] = "hello";
char *tempPtr = NULL;
size_t strSize = strlen(a1)+1;
pa2 = (char *)malloc(strSize * sizeof(char));
memset(pa2, 0x00, strSize);
if(pa2 == NULL)
{
printf("Out Of Memory!");
}
else
{
strcpy(pa2, a1);
tempPtr = pa2; //关键是这边,如果不使用用一个tempPtr,而直接使用pa2的话,看下面:
for(i=0;i < strlen(pa2);i++)
{
printf("%c",*tempPtr++); //这边pa2++就改变了pa2这个指针,下面调用free必须使用p2指针最初的地址值。
}
free(pa2);
pa2 = NULL;
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
unsigned char *pa2 = NULL;
const unsigned char a1[] = "hello";
unsigned char *tempPtr = NULL;
size_t strSize = (strlen((const char *)a1)+1);
pa2 = (unsigned char *)malloc(strSize * sizeof(unsigned char));
memset(pa2, 0x00, strSize);
if(pa2 == NULL)
{
printf("Out Of Memory!");
}
else
{
strcpy((char *)pa2, (const char *)a1);
tempPtr = pa2;
for(i=0;i < strlen((char *)pa2);i++)
{
printf("%c",*tempPtr++);
}
free(pa2);
pa2 = NULL;
}
return 0;
}