firebat 发表于 2011-2-16 23:12:50

指针和strcpy和malloc,求解

先贴上代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char *tmp;
    char *ptr;

    tmp=malloc(sizeof(char)*2);
    scanf("%s",ptr);
    strcpy(tmp,ptr);
   
    printf("ptr:%ld\n",strlen(ptr));
    printf("tmp:%ld\n",strlen(tmp));

      free(tmp);
    return 0;
}


有个不明白的地方:
为指针tmp分配了2个char的内存,为什么不论ptr指向的字符串有多长,strcpy(tmp,ptr)都能执行?

将程序改为以下形式,仍然可以运行:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char tmp;
    char ptr[]="test";

    strcpy(tmp,ptr);
    printf("tmp:%s,sizeof:%ld,\n",tmp,sizeof(tmp));
    printf("ptr:%ld\n",strlen(ptr));
    printf("tmp:%ld\n",strlen(tmp));

    return 0;
}

这里tmp明显没有足够的空间容纳ptr的字符串,为什么还能运行呢?

Tom 发表于 2011-2-18 07:58:22

编译器在分配空间的时候,不是分配你指定的数目,而是N的多少倍,N我忘了是多少了,所以,实际上,一般超出几个字节不会报错,还有就是,如果没有越界到程序外面去,程序也可能不会报错。。。

firebat 发表于 2011-2-18 18:55:31

还是不太明白,那分配空间的时候应该分多少啊?

Tom 发表于 2011-2-19 21:22:55

引用第2楼firebat于2011-02-18 10:55发表的:
还是不太明白,那分配空间的时候应该分多少啊? images/back.gif

当然是需要多少就分配多少啊
比如

char st[]="Hello World!\\n";
char *st2;
st2 = (char *)malloc((strlen(st) + 1) * sizeof(char));
strcpy(st2, st);

firebat 发表于 2011-2-20 22:22:40

但是实际上分配多少都行啊

librehat 发表于 2011-7-28 07:26:27

不行的,分配少了会出错。

leyap 发表于 2012-11-8 14:57:34

多出来的部分应该是写到了未被系统使用的空闲内存区,这个时候就是最危险的时候,因为这个错误很隐蔽,只有在特定的情况下(多写入的那块内存刚好被程序的其它部分使用),才会出错。。。

wang1216 发表于 2013-8-10 10:49:41

页: [1]
查看完整版本: 指针和strcpy和malloc,求解