safeString is a small header which comprises several functions intended to perform common operations with C strings in an easier and safer way. It also contains equivalent macros that provide a simpler interface. All functions that involve string modification guarantee that the result will be a valid string regardless of the input string size.
Include safeString.h in your code. That's it.
All functions and macros return 1 in case of a correct execution, or 0 otherwise
(except strClear), so it is easy to test whether the operation has been done
as intended.
Note that char* input parameters must not contain an uninitialized pointer,
but an array. Also note that the size of a dynamic array can not be obtained
by using sizeof() function, so it must be set explicitly.
void strClear(char* str, int size): Fillsstrwith\0withinsize, thus making a string of length 0.int isStr(char* str, int size): Checks ifstris a valid string withinsize. Returns 0 otherwise.int isEqual(char* str1, char* str2): Returns 1 ifstr1is equal tostr2, or 0 otherwise. Bothstr1andstr2must be valid strings.int safeStrCpy(char* dest, char* src, int size_dest): Copies the maximum possible characters ofsrcstring intodest. Returns 1 if the entiresrcstring has been copied, or 0 otherwise.srcmust be a valid string.int safeStrCat(char* dest, char* src, int size_dest): Concatenates the maximum possible characters ofsrcstring afterdeststring. Returns 1 if the entiresrcstring has been concatenated, or 0 otherwise. Bothsrcanddestmust be valid strings.int safeStrLen(char* str, int size): Returns the number of characters ofstrnot counting the final'\0'. Ifstris not a string, returns 0.
These macros are compatible only with static strings. They provide a simpler interface for the functions above without the need of size information.
STR_CLEAR(str)IS_STR(str)IS_EQUAL(str1, str2)SAFE_STR_CPY(dest, src)SAFE_STR_CAT(dest, src)SAFE_STR_LEN(str)
The only requirement for safeString is string.h, which should be already
installed of most C environments.
A more comprehensive code can be found on test/example.c
#include "safeString.h"
#include <stdio.h>
int main(void)
{
char str1[] = "Hello";
char str2[] = ", world";
char small[10];
char large[100];
STR_CLEAR(small);
SAFE_STR_CAT(small, str1);
SAFE_STR_CAT(small, str2);
SAFE_STR_CPY(large, str1);
SAFE_STR_CAT(large, str2);
printf("small: %s\nlarge: %s\n", small, large);
return 0;
}