This video explains that common C runtime functions like strcpy, strcat, sprintf, scanf, and strtok are unsafe because they don't respect buffer sizes and can cause memory corruption. The safe alternatives are strncpy_s, snprintf_s, scanf_s, and strtok_s, which properly handle buffer sizes and null termination. In C++, using string classes and stringstream provides even safer memory management.
Unsafe C Functions: Secure Coding Strategies for Modern C and C++
Added:Can you spot the bug in this code well I'll make it easier on you by saying there are actually three bugs at least in this code let's take a look at what the function claims to do and how it works and where those bugs are the function accepts two strings a conuscare is string one and a const care string two it then declares a local output buffer of Max path Max path is set to 260 on windows so it's a fair size buffer we then stir copy in our first string we stir cat on a space and we stir cat on our second string we then output it and that should output hello space world if we were to specify hello in world as the two incoming strings the first problem is fairly obvious there's absolutely no respecting the size of the output buffer that you're copying the strings into so if SC stir one and SC stir two were more than 260 characters combined along with the space it was simply walk into memory crash your system and do horrible things how do we solve this well our first try might be to use something that does respect the buffer size stir and copy so this function is much the same but it uses stir and copy to copy the first string into the buffer up to Max path it then uses stir and Cat to add on the space and stir end CAD again to add on the second string then it outputs it so are we done well not quite one of the problems is the end and stir in copy actually represents the number of characters not including the null Terminator so that's our first problem let's fix that by passing maxpath minus one to stir and copy are we golden well unfortunately not quite the problem with stir and copy is that yes it does respect the size of the buffer but if it hits the end of the buffer it just stops it does not add an alternator if stir and copy hits the end of the buffer it simply stops writing characters and does not null terminate the string so your stirring cat is going to wander off into space again how do we fix this well we need a new function stir copy underscore s this is the new C runtime function completely official in the standard hopefully you're aware of it but if not here is your introduction it accepts the output buffer the number of characters to write and the input string however if it does reach the end of the string it does null terminate that means even if the first one was to fill the buffer the stir cat would respect that hey the buffer is already full because there's no more room and I've hit the null Terminator so we'll stop unfortunately this code is rather cryptic and you have to pass Max pass minus one and it's a little weird if we jump into C plus plus we see it gets immensely simpler no these two strings should probably be cost references but being that as it is Stir one and stir two are simply combined with a space in between and then output to the C out using the stream operator and Then followed by an inline which is the new line character all of the memory management is done by the string class itself and as long as you have Heap memory available which is generally always true these days or even virtual memory this function will always succeed and work as you expected there's a whole host of unsafe stir copy functions like stir copy store copy a and w the answer in Unicode versions WCS copy the windows version MBS copy the multi-byte copy version the stir copy a and stir copy a and w elster copy all of these are generally shell and windows functions instead use Stir copy underscore s similarly all of these stir cat functions are also deprecated that's stir cat stir Katy W store ncat and all the shell ones stir cancer Cate stir cat W the L versions elster cat everything that you've generally got used to using over the years is now unsafe to use what's amazing to me is the number of times the dysfunction has been Rewritten by people who still committed the same general errors instead use Stir cat underscore ass which is safe next we turn our attention to sprintef S printf is very much like your standard printf function except instead of writing to the output it writes its characters to a string by now I imagine you can see that the obvious problem here is that if your Source string is longer than your Target string it's going to overflow the buffer and crash our first attempt might be to switch to SN printf however there are problems here using SN printf feels like it might be safe unfortunately there are problems with it as well the size specifier is generally based on the format specifiers that you send in and you've got to remember that those are the minimum widths so even if you carefully calculated the resulting output string might still be larger than what you expect this function handles that by returning the number of bytes that it wrote and it's up to you to check this code hover does not check Sprint FS is the safe version that properly respects the buffer size you pass in and does generally exactly what you suspect now in the event it doesn't fit you should check the return value to see how many characters are written but it's safe and won't trash memory as before there's a whole host of printf functions into Strings that are not safe Sprint FW and a the answer Unicode versions the Ws printf all of these getting up to wvsn printfw all the Legacy SN printf functions are ambiguous about whether or not they null terminate the buffer when the limit is reached and so you should use SN printf underscore s instead I to a could it get much simpler and yet it's still not safe in this case we pass in two integers and we declare two output buffers we then print them with a space in between and that should work and in fact this will because we've declared outrageously large buffers of 260 characters instead of the small amount that it actually needs and so your two options are to declare really large buffers that are wasteful or to run the risk of trashing memory how do we fix it well you've probably guessed by now I to a underscore s first we calculate the length of the two buffers we're going to use the count of operator in C which is reasonably new so you may not be familiar with it the difference is that instead of returning the size of the array and bytes like size of wood it Returns the number of elements or the count of elements in that array once we have the two lengths we can include those in our new call to I to a underscore s which will respect the output buffer length of course in this example we are still declaring large buffers but we could have gone with 16 instead of Max path strength tokenization is a concept that a lot of people understand in general but haven't written code to do what it does is it walks an input string and breaks it into words at the delimiter that you specify the original C versions modify your buffer in place and then it returns a pointer to the next place in the string after the token where you pick up again so if you tokenize hello you big fat Wonderful World on Space it would yield all six words individually let's look at a classic example of tokenizing a string first we call stir toke to obtain the first token and while the token is not null we print it out with a space and then search for the next token when we're done we use put as to terminate the line now the problem here is that it's partying on your memory and you have no idea how big your memory is so by using stir toke underscore s we can do it safely rather than modifying the string in place it provides you with another value rest which is where the rest of the string can be found so in this case we call Sir toke underscore s to get the first token and where to pick up and then we continue looking for tokens updating the rest variable each time when we're done we put out that same new line and it should output exactly what we want and do it safely in C plus plus it's similar but much easier we're going to use a string stream initialized from the input string and we're going to use getline to read stuff out of it as we do those tokens we're going to call C out and in the token and a space when we're done we upload an end line and everything works exactly as expected scan F or string scan F reading from strings is another area where people run into trouble given an input string such as hello world you then give it a format specifier that indicates what it expects to find in the string it's basically operates the inverse of printf so if we're looking for the two strings in that one larger string separated by a space we could ask for a percent s space percent s the original C versions though have no support for output buffer links if hello is longer than expected it's going to overwrite memory here's an unsafe example we passed in the input string and we declare two output buffers we then read the two strings which we expect to be separated by a space into outstring one and out string two and then print them back out with a space in between the problem here again is that outstring 1 and outstring two are of unknown length to fix that we use scanf underscore s and here's how you use it again we calculate the length of the two output buffers with the count of operator and then we're going to scan those two strings in after the format specifier comes each of the variables but in this case if each is accompanied by a length so our first output variable is outstring one and it is len one long our second one is out string two and it is land two long this works perfectly and will never corrupt memory generally you can assume that all of the Legacy functions here are unsafe for scanf and you should instead use scanfs or snfs instead if you have any interest in matters related to autism Asperger's or ASD or perhaps know somebody that is impacted by them please check out my book on Amazon secrets of the autistic millionaire it's got nothing to do with money and everything to do with living a successful life on the Spectrum essentially it's everything I wish I'd known back then that I know now in the meantime please like And subscribe the channel and I'll do more videos like this one if it turns out to be well received in the meantime and in between time I hope to see you next time right here in Dave's Garage
Up Next

Art Nouveau Design: History, Characteristics, and Key Figures
@InteriorDesignHub
34.6K views•2021-11-22

IFS Therapy Demonstration: Complete Session with Unburdening
@IFSCA
95.9K views•2021-01-13

FastAPI vs Flask vs Django: Choosing the Right Python Web Framework
@TechWithTim
302.5K views•2024-05-26

Game of Thrones Opening Credits: A Cinematic Analysis
@gameofthrones
46.3M views•2011-04-18
Related Study Plans & Knowledge Roadmaps
Structured learning paths in General & Interdisciplinary Studies

























![[MUC++] Daniel Pfeifer - "Effective CMake"](https://i.ytimg.com/vi/rLopVhns4Zs/sddefault.jpg?sqp=-oaymwEmCIAFEOAD8quKqQMa8AEB-AH-CYAC0AWKAgwIABABGGUgYChSMA8=&rs=AOn4CLC36AvSuYNmyosZP6TB_M9SrLl_pA)






![[MUC++] Peter Sommerlad - "C++ Core Guidelines - Safer C++"](https://i.ytimg.com/vi_webp/RcPX7rhS5Lg/maxresdefault.webp)











