使用动态存储分配来创建字符串的副本。运行的结果不对!
代码
程序代码://编写名为duplicate的函数,此函数使用动态存储分配来创建字符串的副本
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *my_malloc(int n);
char *duplicate(const char* str);
int main(void)
{
char *str = my_malloc(1 * sizeof(char));
gets(str);
char *p ;
p = duplicate(str);
if(p == NULL)
{
printf("Error:duplicate failed in concat\n");
exit(EXIT_FAILURE);
}
putchar('\n');
// printf("p = %d\n",strlen(p));
puts(p);
return 0;
}
char *my_malloc(int n)
{
char *p = malloc(n);
if(p == NULL)
{
printf("Error:malloc failed in concat\n");
exit(EXIT_FAILURE);
}
return p;
}
char* duplicate(const char* str)
{
int n = strlen(str);
char *p = malloc(sizeof(char) * n + 1);
if(p == NULL) //分配内存失败返回空指针
return NULL;
strcpy(p,str);
return p;
}
为什么运行的结果每次都复制在第十三的字符就结束。
111111111111111111111111111111111111
111111111111111111111111111111111111
111111111111111111111111111111111111
p = 13
1111111111111







