A double free is occurring because you free the buffer here:
if( recvfrom(sockfd, buf, buflen, 0, (struct sockaddr*)&serv_addr, &slen) == -1){
close(sockfd);
free(buf);
And then again when you exit the function:
memcpy(reply, buf, BUFLEN);
close(sockfd);
free(buf);
return 0;
To fix that, once you free buf
, set the pointer to NULL
:
if( recvfrom(sockfd, buf, buflen, 0, (struct sockaddr*)&serv_addr, &slen) == -1){
close(sockfd);
free(buf);
buf = NULL;
There is also an issue where you are potentially reading from buf
after it has possibly been free'd. (note the memcpy
above.)