Added some guard clauses and additional checks when allocating memory.

This commit is contained in:
2022-06-30 23:18:29 -05:00
parent 0874579e92
commit 0f2c6fe9ed
+19 -6
View File
@@ -1,4 +1,5 @@
#include "tstring.h"
#include <string.h>
int GetGlyphByteWidth(const char* glyph);
void TStringCopyGlyph(const char* glyph, int length, TString* string);
@@ -13,8 +14,22 @@ struct __tstring {
TString* TStringCreate(void) {
TString* string = malloc(sizeof(TString));
if (!string) {
fprintf(stderr, "Failed to malloc space for TString. %s.\n", strerror(errno));
return NULL;
}
string->Characters = calloc(DEFAULT_TSTRING_BYTE_BUFFER, sizeof(char));
if (!string->Characters) {
fprintf(stderr, "Failed to malloc space for TString character array. %s.\n", strerror(errno));
free(string);
return NULL;
}
string->Capacity = DEFAULT_TSTRING_BYTE_BUFFER;
string->ByteCount = 0;
string->Length = 0;
@@ -29,6 +44,8 @@ int TStringLength(const TString* string) {
}
void TStringAppendText(const char* text, TString* string) {
if (!text || !string) return;
int totalLength = strlen(text);
int glyphLength = GetGlyphByteWidth(text);
@@ -94,12 +111,7 @@ void TStringFree(TString* string) {
}
int GetGlyphByteWidth(const char* glyph) {
// printf("Bytes for '%s': ", glyph);
// for(size_t i = 0; i < strlen(glyph); i++) {
// printf("%02X ", 0xFF & glyph[i]);
// }
// printf("\n");
if (!glyph) return -1;
if ((*glyph & 0x80) == 0) {
return 1;
@@ -118,6 +130,7 @@ int GetGlyphByteWidth(const char* glyph) {
}
void TStringCopyGlyph(const char* glyph, int length, TString* string) {
if (!glyph || !string) return;
if (length < 1) return;
if (string->ByteCount + length > string->Capacity) {