I wish to implement a web socket handshake and for that I am using the following code snippet.
But I get segmentation fault when I start freeing the memory which I allocate dynamically. Error shows up in the place where I use free function for the first time. Please help.
char rbuf[656];
char handshake[800];
char *handshake_part2, *handshake_part3,*key,*magic,*final;
unsigned char hash [20];
key=strndup(rbuf+359, 24);
magic = malloc(strlen("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")+2);
strcpy(magic,"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
final = malloc (60);
final = strcat(key,magic);
SHA1(final,strlen(final),hash);
base64(hash, sizeof(hash));
handshake_part2= malloc(400);
handshake_part2= base64(hash, sizeof(hash));
strcpy (handshake,"HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: Websocket\r \nConnection: Upgrade\r\nSec-WebSocket-Accept: ");
strcat(handshake,handshake_part2);
handshake_part3= malloc(400);
handshake_part3="\r\nWebSocket-Origin: http://localhost:9605\r\nWebSocket-Location: ws://localhost:9609/\r\n\r\n";
strcat(handshake,handshake_part3);
printf("Response Header :\n%s", handshake);
free(handshake_part3);
handshake_part3=NULL;
printf("Free 1");
free(handshake_part2);
handshake_part2=NULL;
printf("Free 2");
free(final);`
final=NULL;
printf("Free 3");
free(magic);
magic=NULL;
printf("Free 4");
free(key);
You are reassigning
handshake_part3to be the constant string"\r\n..."; did you mean tostrcpy()(preferablystrncpy()or equivalent!) this in instead?