BillyYu

求助:HELLO WORLD用C时的怪状况

先贴一段代码
#include <stdio.h>
#include 
<cs50.h>
#include 
<stdlib.h>
#include 
<string.h>

int 
main(
int argc, char *argv[])    {
    printf(
"Input a string:");
    
char *text=GetString();

    
char *tmp=(char *)malloc(sizeof(char* strlen(text));
    memcpy(tmp,text,strlen(text));

    printf(
"%s\n%s\n",text,tmp);
    
return 0;
}

再贴奇怪的现象
zhihua@ThinkPad (~/cs50/2009fall/psets/2): make test
gcc -ggdb -std=c99 -Wall -Werror -Wformat=0    test.c  -lcs50 -lm -o test
zhihua@ThinkPad (~/cs50/2009fall/psets/2): ./test
Input a string:HELLO WORLD
HELLO WORLD
HELLO WORLD
zhihua@ThinkPad (~/cs50/2009fall/psets/2): ./test
Input a string:HELLO,WORLD
HELLO,WORLD
HELLO,WORLD
zhihua@ThinkPad (~/cs50/2009fall/psets/2): ./test
Input a string:HELLO, WORLD
HELLO, WORLD
HELLO, WORLDy
很奇怪这个‘y'是怎么出现的呢?
又测了一把,发现只要是输入12个字符长度的时候,这个‘y’就会出现。请高手相告

posted on 2011-01-17 00:00 志华 阅读(1693) 评论(7)  编辑 收藏 引用 所属分类: Ubuntu

评论

# re: 求助:HELLO WORLD用C时的怪状况[未登录] 2011-01-17 00:47 Eric

应该是没有拷贝串结束符  回复  更多评论   

# re: 求助:HELLO WORLD用C时的怪状况[未登录] 2011-01-17 01:23 R

楼上正解. 做字符串拷贝的时候尽量用strcpy/strcpy_s. 如果一定要用memcpy, 拷贝的字节数量应该是strlen+1, 因为在字符串最后需要加上'\0'  回复  更多评论   

# re: 求助:HELLO WORLD用C时的怪状况 2011-01-17 08:08 hello

// 试试
char *tmp=(char *)malloc(strlen(text) + 1);
if (tmp) {
memcpy(tmp,text,strlen(text));
printf("%s\n%s\n",text,tmp);
free(tmp);
}  回复  更多评论   

# re: 求助:HELLO WORLD用C时的怪状况 2011-01-17 08:18 w

char *tmp=(char *)malloc(strlen(text) + 1);
if (tmp) {
strcpy(tmp,text);
printf("%s\n%s\n",text,tmp);
free(tmp);
}  回复  更多评论   

# re: 求助:HELLO WORLD用C时的怪状况[未登录] 2011-01-17 15:44 tommy

char *text=GetString();
char *tmp=(char *)malloc(sizeof(char) * strlen(text));

I think u should change to
char *text=GetString();
char *tmp=(char *)malloc(sizeof(char) * (strlen(text) + sizeof(char)));
  回复  更多评论   

# re: 求助:HELLO WORLD用C时的怪状况 2011-01-17 21:12 志华

@R
试了 strlen+1的方法,确实如此。
但是为啥在11个字符之前是没有问题的,13个字符之后也是没有问题的,独独这12.。。。  回复  更多评论   

# re: 求助:HELLO WORLD用C时的怪状况[未登录] 2011-01-18 14:22 Lucifer

@志华
这个很简单啊,因为前面11个只是因为最后一个byte正好是0(随机的),所以显示出来的也是正确的,但是12个的时候,最后一个byte不是0,是y(随机的),所以显示出错了……  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2011年1月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
303112345

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

文章档案

搜索

最新评论

阅读排行榜

评论排行榜