Socket accept is consuming my memory on windows without release

c, gcc, memory-management, sockets, windows

Solution

On Windows, winsock uses `closesocket` to properly close and cleanup a socket.

Problem

I have written a very small function in C, opens a socket, accepts connection and immediately closes them. The problem is, each connections eats some memory without releasing it at anytime to the OS. I ran ab (apache benchmark) with about 300K requests, and the processes memory is continuously growing (at the end few hundred megabytes). I'm aware that a process is not always returning its free memory to the OS. But as soon as it gets over few megabytes, I think it should return the memory or am I wrong? This happens only on Windows. On Linux is my memory usage all the time nearly the processes startup usage. Compiled with GCC 4.8.2. Tested on Windows Server 2008 R2 and Windows 8.1. ``` void http_server_start(void) { int rc; struct sockaddr_in cfg; #ifdef _WIN32 WORD ver; WSADATA data; ver=MAKEWORD(2,2); rc=WSAStartup(ver, &data); if(rc != 0){ printf("Error: Unable to initialize WSA (%d)", rc); } #endif memset(&cfg, 0, sizeof(cfg)); cfg.sin_family = AF_INET; cfg.sin_addr.s_addr = htonl(INADDR_ANY); cfg.sin_port = htons(PORT); server = socket(AF_INET, SOCK_STREAM, 6); int reuseaddr=1; if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, (char*)&reuseaddr, sizeof(reuseaddr)) == -1){ rc=GetLastErrorEx(); printf("Error: Unable to set SO_REUSEADDR (%d)\n", rc); } else if (bind(server, (struct sockaddr *)&cfg, sizeof(cfg)) < 0 ) { rc=GetLastErrorEx(); printf("Error: Unable to bind socket (%d)\n", rc); close(server); } else if (listen(server, QUEUE_SIZE) < 0) { rc=GetLastErrorEx(); printf("Error: Unable to listen (%d)\n", rc); close(server); } else { printf("Listening on %s:%d\n", inet_ntoa(cfg.sin_addr), ntohs(cfg.sin_port)); int client; struct sockaddr_in addr; int addrlen=sizeof(addr); do { client=accept(server, (struct sockaddr*)&addr, &addrlen); if(client != -1){ shutdown(client, SHUT_RDWR); close(client); } } while(1); } } ```

Original source