feat: safer `free()'s

`free' allocated buffers only on success inside the main loop, and
`free' them on error inside their respective functions

(fixes an UB where an already freed buffer is freed again in the main
loop)
main
Tom MTT. 1 year ago
parent be74fa43cc
commit 6c57a4d03c

@ -13,6 +13,7 @@
#include "bin.h"
#include <errno.h> /* for errno */
#include <stdio.h> /* for NULL, fclose, fopen, fputs, snprintf, FILE */
#include <stdlib.h> /* for calloc, free, malloc, rand, realloc */
#include <string.h> /* for strlen */
@ -39,8 +40,11 @@ char *generate_id(int min_length)
/* for each letter, generate a random one */
for (int i = 0; i < length; i++) {
if (i > 8 * min_length)
if (i > 8 * min_length) {
errno = EFBIG;
free(buffer);
return NULL;
}
buffer[i] = id_symbols[rand() % strlen(id_symbols)];
buffer[i + 1] = 0;
@ -55,6 +59,7 @@ char *generate_id(int min_length)
free(buffer);
return NULL;
}
buffer = tmp;
}
}

@ -340,6 +340,8 @@ int main(int argc, char *argv[])
send_response(connection, url);
verbose(1, "All done.");
free(url);
} else {
error("error while making a valid URL.");
send_response(connection, "Could not create your paste URL.\nPlease try again later.\n");
@ -348,10 +350,14 @@ int main(int argc, char *argv[])
error("error while writing paste to disk.");
send_response(connection, "Could not write your paste to disk.\nPlease try again later.\n");
}
free(id);
} else {
error("error while generating a random ID.");
send_response(connection, "Could not generate your paste ID.\nPlease try again later.\n");
}
free(paste);
} else {
if (errno == EFBIG)
send_response(connection, "Paste too big.\n");
@ -365,11 +371,6 @@ int main(int argc, char *argv[])
error("error %d while reading paste from incoming connection.", errno);
}
/* free resources */
free(paste);
free(id);
free(url);
/* close connection */
close_connection(connection);
}

Loading…
Cancel
Save