开发者

Is there any reason this function call shouldn't work?

When executing the following, GDB says it's failing at the last line of data():

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: 13 at address: 0x0000000000000000
0x00000001000021ee in data (srvr=Cannot access memory at address 0x6567612d726572fd
 ) at /Users/Documents/w11/cs176b/mftp/data.c:121

Do you see any 开发者_C百科reason why it would fail?

global in control.c, eventually gets strcpy()'d an IP address x.x.x.x

char passive_ip[25] = ""; 

called within control.c

data(passive_ip, passive_port); 

data.c

void data(char* srvr, int prt) { 
    printf("In Data: connecting to %s:%i", srvr, prt);

    struct hostent *hp = gethostbyname(srvr);

    if (hp == NULL) {
        printf("gethostbyname() failed\n");
    } else {
        printf("%s = ", hp->h_name);
        unsigned int i=0;
        //  while ( hp -> h_addr_list[i] != NULL) {
        printf( "%i %s ",i, inet_ntoa( *( struct in_addr*)( hp -> h_addr_list[0])));
        //      i++;
        //  }
        printf("\n");
    }

    char hostname[15];
    strcpy(hostname, inet_ntoa( *( struct in_addr*)( hp -> h_addr_list[0])));


    int sockfd;
    int len;
    struct sockaddr_in address;
    int result;
    char* buffer;


    /*  Create a socket for the client.  */
    sockfd = socket(PF_INET, SOCK_STREAM, 0);

    /*  Name the socket, as agreed with the server.  */
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr(  hostname    );
    address.sin_port = htons(prt);
    len = sizeof(address);

    /*  Now connect our socket to the server's socket.  */
    result = connect(sockfd, (struct sockaddr *)&address, len);

    if(result == -1) {
        perror("oops (data): client3");
        exit(1);
    }

    read(sockfd, buffer, MY_BUFFER_SIZE);


} // this is line 121


The first thing I'd be doing is changing:

char hostname[15];

to:

char hostname[16];

You may well be overflowing the buffer, which would cause stack corruption. A full IPv4 address needs 16 characters: nnn.nnn.nnn.nnn plus a terminating \0. In reality, you probably shouldn't be using those calls if you're the least bit interested in handling IPv6 - I'm pretty certain they don't play well in that world. But that's a different issue.


The other problem you have (and this is almost certainly the cause of your crash) is that you do:

char *buffer;
:
read(sockfd, buffer, MY_BUFFER_SIZE);

without actually allocating memory for that buffer, so that buffer will point to some arbitrary location. Either use:

char buffer[MY_BUFFER_SIZE];

or:

char *buffer = malloc (MY_BUFFER_SIZE);

remembering to check for allocation failure and free it when no longer required.


The last line of the function data() is the read(). You are trying to read data into buffer; you have not allocated any storage for buffer, so the pointer is (luckily for you) NULL, leading to the crash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜