The Rules of Buffer In C
Buffer or String in C is represented as an array of
char terminated by null character
Null character is not the part of
buff length but it does requires a memory space.
The problem is in the function for handling a string operation like allocation
strcpy(dest, src) and concatination
strcat(dest, src) is performed in unsafe way.
malloc only allocate memory for us without initialize it which potentially have a garbage values (a values from previous operation that are not cleared). Where
strcat is assume that
dest is big enough which lead us buffer overflow problem if the
src is larger than
This is a list of rules that I always follow when dealing with buffer
1. Allocation: Use calloc instead
calloc will allocate
LEN contiguos block of memory with size
sizeof(char)bytes for each block and initialize it to zero. This will make sure that
buff is not contains any garbage values or sensitive information from the previous operation.
2. Copy: Use strncpy and terminate.
strncpy is copy all the first
sizeof(buff) - 1 from
src. This help us prevent buffer overflow and corrupting the heap.
3. Concat: Use strncat
This will make sure that the concat operation is not write to more than allocated memory for