user19628924
user19628924

Reputation:

If the socket() function fails should I close the socket?

If the socket() function fails and returns -1, should I close the socket or not because it already couldn't create a socket?

Upvotes: 1

Views: 102

Answers (1)

chqrlie
chqrlie

Reputation: 144540

Obviously if socket() returned -1 you do not have a valid handle to pass to close(). So no, there is no need to close the socket, it was not created. The same applies to open() or creat() retuning -1.

Note that if you inadvertently pass -1 to close(), nothing bad will happen as the OS will just report an invalid handle, which the C library system call wrapper will handle by returning -1 setting errno to EBADF.

This is in contrast to passing fclose() the null stream pointer returned by fopen() in case of failure: The C Standard explicitly says this has undefined behavior and some implementations will not check for a null pointer and cause a segmentation fault by dereferencing the null pointer, thus terminating the program.

Also note that if bind(), listen() or connect() fail on a valid socket handle returned by socket(), then you do need to close the socket when done with it, after potentially retrying these calls.

Upvotes: 3

Related Questions