'why socket(AF_INET, SOCK_STREAM, 0) returns 1434, which is over 1024, then make program crash

when I invoke the function on Linux(ubuntu):

socket(AF_INET, SOCK_STREAM, 0)

It returns 1434, which is over 1024.

Then, the program crashed at here:

fd_set read_fd;
FD_ZERO(&read_fd);
FD_SET(fd, &read_fd);

It seems like fd is over 1024, and the FD_SETSIZE macro is only 1024. so, it makes "buffer overflow detected" core dump.

I also write a demo c++ program:

#include <sys/socket.h>
#include <stdio.h>
int main() {
  int fd = socket(AF_INET, SOCK_STREAM, 0);
  printf("fd value is %d\n", fd);
  return 0;
}

and the stdout of the program is:

fd value is 3


Solution 1:[1]

why socket(AF_INET, SOCK_STREAM, 0) returns 1434, which is over 1024

Because of whatever reasons the library implementation had to return such descriptor. Possibly, the program tried to open more than 1024 simultaneous file descriptors.

In short, the solution is to not use fd_set at all. You're probably using it for select. Don't use that API. Use one of the API's that have supplanted it, such as poll. Or alternatively open fewer file descriptors.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eerorika