EN VI

Safest possible way to concatenate strings in C?

2024-03-11 05:00:06
How to Safest possible way to concatenate strings in C

strcat is extremely unsafe strcpy is also extremely unsafe. sprintf is the almost unsafe.

Don't have sprintf_s, strcpy_s or any _s functions available to me.

Please tell something from all the basic available libraries like stdio.h, stdlib.h, string.h. Or create any custom function to do it. I don't need something "safer" I need the "safest" possible one. Other posts mentioned only _s functions and strncat being "safer" which doesn't answer my question.

Concatenation string types: const char*, and function must return answer in const char* format.

Tried all strcpy, strcat, sprintf functions in every possible way but didn't get any result.

please tell answer in this format:

const char* func(const char* s1,const char* s2){
    //process concated_const_str=s1+s2
    return concated_const_str;
}

Objective creitaria of measuring the safety of the function: any possible memory leaks must be handled carefully.

Solution:

The 100% safe, fully generalized approach uses snprintf, twice. The first call passes NULL as the buffer to write to, and a bufsz of 0, and it doesn't actually format anything, but returns the amount of characters (excluding the NUL terminator) required. You allocate one byte more than returned, and pass that new buffer and incremented buffer size to a second call to snprintf with the same format string and inputs, and it populates the string as you want.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login