因为我知道当我们访问未由操作系统分配的内存位置时会发生分段错误,这是什么导致相同的?
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main(int argc,char* argv[])
{
if(argc<3 || argc>4)
{
//diewithusermsg("Parameters","<Server_Address> <Echo_String> <Port_number>");
}
const char* servip = argv[1];
char* echostring = argv[2];
in_port_t servport = (argc==4)?atoi(argv[3]):7;
int sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sock<0)
{
//diewithsysmsg("socket() failed");
}
struct sockaddr_in servaddr;
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family=AF_INET;
int rtnval = inet_pton(AF_INET,servip,&servaddr.sin_addr.s_addr);
return 0;
}
在inet_pton的servip参数
答案 0 :(得分:1)
如果未将参数传递给程序,程序将崩溃。传递参数并且不会崩溃:
> valgrind ./a.out 127.0.0.1 foo 80
==22863== Memcheck, a memory error detector
==22863== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==22863== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==22863== Command: ./a.out 127.0.0.1 foo 80
==22863==
servip: 127.0.0.1
==22863==
==22863== HEAP SUMMARY:
==22863== in use at exit: 0 bytes in 0 blocks
==22863== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==22863==
==22863== All heap blocks were freed -- no leaks are possible
==22863==
==22863== For counts of detected and suppressed errors, rerun with: -v
==22863== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
代码不变:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main(int argc,char* argv[])
{
if(argc<3 || argc>4)
{
//diewithusermsg("Parameters","<Server_Address> <Echo_String> <Port_number>");
}
const char* servip = argv[1];
char* echostring = argv[2];
in_port_t servport = (argc==4)?atoi(argv[3]):7;
int sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sock<0)
{
//diewithsysmsg("socket() failed");
}
struct sockaddr_in servaddr;
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family=AF_INET;
fprintf( stderr, "servip: %s\n", servip );
int rtnval = inet_pton(AF_INET,servip,&servaddr.sin_addr.s_addr);
return 0;
}