The chktype function allocates memory for an automatic variable on the stack, and then returns the address of this variable (i.e. a pointer to this variable).
The problem is that the variables allocated on the stack are automatically destroyed when they go out of scope (i.e., control passes outside the curly braces that define the function).
This means that you are essentially returning a pointer to an invalid memory location, which is bad news. In C-talk, this behavior is undefined. In practical terms, this leads to poor results or, possibly, even to failure.
char *chktype(char *Buffer, int Size) {
The correct way to return char* from a function is to allocate new memory from the heap using the malloc (or calloc ) function. This means that the calling function will be responsible for freeing the memory used by the return value, otherwise your program will leak memory.
(Always put this requirement in the documentation for your function! Even if βdocumentationβ means a comment above the declaration.)
For example, change your code like this:
char *chktype(char *Buffer, int Size) {
Now, in the chktype calling function, you need to make sure that you call free when you are done with its return value:
char *type = chktype(...); // do something free(type);
Please note that reliable code should check the malloc result for the null pointer to make sure that it could not allocate the requested memory. If so, you need to handle the error somehow. For clarity, this is not shown above.