Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C OSX上的inet_ntoa()分段错误_C_Macos_Sockets_Gcc - Fatal编程技术网

C OSX上的inet_ntoa()分段错误

C OSX上的inet_ntoa()分段错误,c,macos,sockets,gcc,C,Macos,Sockets,Gcc,我遇到一个问题,inet_ntoa导致OSX上出现分段错误, 这在Linux上不会发生 我的测试代码如下 // sample.c #include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> //#include <arpa/inet.h> // adding this line prevents the segfault

我遇到一个问题,inet_ntoa导致OSX上出现分段错误, 这在Linux上不会发生

我的测试代码如下

// sample.c
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
//#include <arpa/inet.h>  // adding this line prevents the segfault

int main() {
    struct sockaddr_in addr;
    struct sockaddr_in client;

    int sock0 = socket(AF_INET, SOCK_STREAM, 0);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(12345);
    addr.sin_addr.s_addr = INADDR_ANY;

    bind(sock0, (struct sockaddr *)&addr, sizeof(addr));
    listen(sock0, 5);

    while (1) {
        int len = sizeof(client);
        int sock = accept(sock0, (struct sockaddr *)&client, (socklen_t *)&len);
        printf("accepted connection from %s, port=%d\n",
               inet_ntoa(client.sin_addr), ntohs(client.sin_port));
        send(sock, "HELLO", 5, 0);
        close(sock);
    }

    close(sock0);

    return 0;
}
//sample.c
#包括
#包括
#包括
#包括
//#include,它添加了一个include“arpa/inet.h”。
我确认inet_ntoa肯定是在inet.h中声明的,我确信这是正确的方式

但是我不明白为什么没有它这个代码就不能工作。当我在没有包含行的情况下构建和链接此代码时会发生什么

我知道构建此代码时会显示“隐式函数声明”警告,但不会发生链接错误。 我认为,这意味着linker以某种方式找到了inet_ntoa的实现。 这是错的吗


谢谢!非常感谢您的建议。

我猜您的OSX系统是64位的,而Linux系统是32位的。假定未声明的函数返回整数。如果64位指针衰减为32位整数,作为指针取消引用,则可能会出现分段错误。

C允许隐式声明函数()。这就是为什么您没有得到编译器错误。此外,inet_ntoa位于glibc中,默认情况下由gcc链接,因此链接器会找到函数的定义,因此不会出现链接器错误。segfault发生的原因是:1)C假设函数返回一个int,2)glibc中Mac inet_ntoa返回一个64位指针,该指针被转换为32位值并丢失信息