N mol
N mol

Reputation: 571

Segmentation fault while freeing memory

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);

Upvotes: 0

Views: 331

Answers (4)

YePhIcK
YePhIcK

Reputation: 5856

Look at this code:

final = malloc (60);
final = strcat(key,magic); 

what you do is you abandon the newly allocated final and override it with a key's address. later on you delete it twice (once via final and than via key), which is not allowed.

That's the only thing I noticed at a glance but I have a feeling there may be more...

Edit: And looking at other answers I can see there are indeed "more"

Upvotes: 0

Eran
Eran

Reputation: 22010

handshake_part3= malloc(400); 
handshake_part3="\r\nWebSocket-Origin: http://localhost:9605\r\nWebSocket-Location: ws://localhost:9609/\r\n\r\n";

You assign a string literal to handshake_part3, and then try to free it... This causes the mallocated buffer to leak, and your free to crash. You should strcpy that string literal to the allocated buffer, or avoid the allocation and the freeing.

Upvotes: 1

Wug
Wug

Reputation: 13196

You're freeing a constant string. The memory is leaking because after you call malloc, you assign the constant string (and the malloc'd memory is leaked).

Upvotes: 2

Philip Kendall
Philip Kendall

Reputation: 4314

You are reassigning handshake_part3 to be the constant string "\r\n..."; did you mean to strcpy() (preferably strncpy() or equivalent!) this in instead?

Upvotes: 3

Related Questions