Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading