大神帮看看使用strcat函数造成这种情况的原因
int main(int argc, char **argv){FILE *sfp,*rfp;
struct sockaddr_in servaddr;
char strbuf[1024],sendbuf[8192],recvbuf[8192],tmpbuf[8192];
char *sip,*spaketno,*sport,*shead;
int port,head,flag=0;
int sockfd, n;
if(argc<5){
printf("usage: --ip --port --paketno --head\n");
return -1;
}
sip = (char *) malloc(sizeof(argv[1]));
sport = (char *) malloc(sizeof(argv[2]));
spaketno = (char *) malloc(sizeof(argv[4]));
shead = (char *) malloc(sizeof(argv[4]));
sip = argv[1];
port = atoi(argv[2]);
spaketno = argv[3];
head = atoi(argv[4]);
spaketno = argv[3];
shead = argv[4];
printf("sip=[%s],sport=[%s],spaketno=[%s],shead=[%s],sip-size=[%d],spor-size=[%d],spaketno-size=[%d],shead=[%d]\
,&sip=[%d],&sport=[%d],&spaketno=[%d],&shead=[%d]\n",sip,sport,spaketno,shead,strlen(sip),sizeof(sport),strlen(spaketno),sizeof(shead),&sip,&sport,&spaketno,&shead);
printf("shead=%s\n",shead);
strcat(spaketno,",");
printf("shead=%s\n",shead);
printf("sip=[%s],sport=[%s],spaketno=[%s],shead=[%s],sip-size=[%d],spor-size=[%d],spaketno-size=[%d],shead=[%d]\
,&sip=[%d],&sport=[%d],&spaketno=[%d],&shead=[%d]\n",sip,sport,spaketno,shead,strlen(sip),sizeof(sport),strlen(spaketno),sizeof(shead),&sip,&sport,&spaketno,&shead);
return 0;
}
在上面代码中
程序执行完 strcat(spaketno,",");这一行后shead变量的值直接变成空的了
一开始怀疑是逗号把shead的内存给占用了,但是打印出各个变量的值发现他们的地址虽然挨着,但是还是有8个字节的间距的。
程序运行时用了如下参数:127.0.0.1 16000 3001 10
运行结果:
root@/bbwgw/sim/yinqi> send 127.0.0.1 16000 3001 10
sip=[127.0.0.1],sport=[],spaketno=[3001],shead=[10],sip-size=[9],spor-size=[8],spaketno-size=[4],shead=[8],&sip=[-788757224],&sport=[-788757240],&spaketno=[-788757232],&shead=[-788757248]
shead=10
shead=
sip=[127.0.0.1],sport=[],spaketno=[3001,],shead=[],sip-size=[9],spor-size=[8],spaketno-size=[5],shead=[8],&sip=[-788757224],&sport=[-788757240],&spaketno=[-788757232],&shead=[-788757248]
[此贴子已经被作者于2017-4-2 17:55编辑过]