E02: Stupid C++ Tricks: Most Dangerous C Functions (E02)

Sdílet
Vložit
  • čas přidán 9. 09. 2024
  • Retired Microsoft engineer Dave Plummer takes you on a tour of security features made for Windows XP SP2 and then details how to make some of the same improvements to your own code, including the use of the safe string functions in the C++ runtime. From strlen to vsnprintf_s, odds are you'll learn something new to keep in your toolbox!
    Code on Github: github.com/dav...
    Snow Crash: amzn.to/3yDQ9o5
    Writing Secure Code, 2nd Edition: amzn.to/3Buh33z

Komentáře • 645

  • @DavesGarage
    @DavesGarage  Před 3 lety +568

    I bet those downvotes are for the haircut!

    • @twobob
      @twobob Před 3 lety +14

      If you recommend anything. Someone else will have an alternate "better" recommendation. "Internet" hey ho . Dang this coffee tastes good

    • @geoffreyanderson2285
      @geoffreyanderson2285 Před 3 lety +18

      Haters gotta hate. I love when there is a new "Dave's Garage" episode...

    • @Hauketal
      @Hauketal Před 3 lety +3

      All those safe functions should return the same value as their unsafe counterparts, and return values should be checked. Unless completely unuseful like for strcpy. Don't teach ignoring return values.

    • @bryanpratt3933
      @bryanpratt3933 Před 3 lety +9

      Engineer/Developer haircuts are functional: Maximum hat compatibility, covers the basics while limiting vulnerabilities and potential exploits.
      Video suggestions:
      - Projects you worked on which impressed you with elegant or clever code solutions
      - Worst production code you ever saw (bonus if you had to fix it)
      - Coding "pet peeves" (bonus if they are pedantic or inconsequential!)
      Enjoy your videos!

    • @DavidWonn
      @DavidWonn Před 3 lety +12

      The haters preferred C-- over C++

  • @danielbuenrostro
    @danielbuenrostro Před 3 lety +446

    > 30 years of experience in C/C++
    > Finally getting good

    • @superscatboy
      @superscatboy Před 3 lety +4

      Lol

    • @chur8260
      @chur8260 Před 3 lety +3

      I done an IRL lol at that.

    • @ernopakarinen9361
      @ernopakarinen9361 Před 3 lety +4

      30 Years is a good pratice time :)

    • @SianaGearz
      @SianaGearz Před 3 lety +19

      Eh, in 10 years he'll be saying "40 years of C and C++, finally getting good"
      In 20 years, he'll be saying "50 years of C and C++, finally getting good".
      It never ends.

    • @yamibakura7491
      @yamibakura7491 Před 2 lety +11

      u can never bcm great in C/C++ ... good is the limit

  • @TravisFabel
    @TravisFabel Před 3 lety +10

    I think what I like most about this channel is its all about the code I wrote when I started professionally.. and the code I maintain today. Most Programmer videos on youtube want to focus on much newer topics, and those that do touch on C++ dont really go in deep.. or if they do, not in an entertaining way.

  • @UncleKennysPlace
    @UncleKennysPlace Před 3 lety +382

    How many programmers does it take to write a line of code? _Ten..._ one to write the line, and nine to tell how they could have done it better!
    Edit: I'm always happy when others pronounce the name of a function phonetically.

    • @AbAb-th5qe
      @AbAb-th5qe Před 3 lety +11

      Hey that's what code reviews are all about right?

    • @iDontProgramInCpp
      @iDontProgramInCpp Před 3 lety +4

      One programmer is enough

    • @sophiacristina
      @sophiacristina Před 3 lety +35

      You wasted too many bytes in that comment!

    • @iDontProgramInCpp
      @iDontProgramInCpp Před 3 lety +2

      @@sophiacristina too bad 😶

    • @jaja777
      @jaja777 Před 3 lety +3

      I would rate this joke as SegFault Error.
      That's how bad it is.

  • @VierPuntNul
    @VierPuntNul Před 3 lety +22

    The more I watch your coding episodes, the more respect I get for you and all the other colleagues that had to deal with writing proper secure code. Although I'm not a huge fan of the VS-specific _s functions (when writing cross-platform code), I do understand their value. Very useful and fun to watch your YT clips.

  • @Andrath
    @Andrath Před 3 lety +50

    This all reminds me where I pwned an intern that was so proud of his "unbreakable" C code until I piped a few megabytes of unicode into there. This is invaluable advice.

  • @Jotalou
    @Jotalou Před 3 lety +26

    Having these lessons available is incredible, thank you so much Dave, please keep up the good work.

  • @guitarman13021
    @guitarman13021 Před 3 lety +82

    You have quickly become the best programming channel on CZcams

  • @_ClericalError_
    @_ClericalError_ Před rokem +6

    Mister Plummer, this is an amazing series and even though this is only the second episode, you are giving out invaluable information for practical programmers. Please keep it up!

  • @ErginSalih
    @ErginSalih Před 3 lety +6

    I use these all the time and have converted a lot of code to use these as well. Worth the effort for more secure code.

  • @jkramerks
    @jkramerks Před 3 lety +4

    I once inherited a project that compiled and had about 25000 warnings on compile. I took the time to make it compile at /w4 as well, but never turned on errors. If anyone ever checked in code that made warnings in the future, I took that as a teachable moment, because half the warnings I fixed were actual bugs or potential outright terminate process errors provided the right conditions. Who knows how many security issues, that wasn't my end goal but a benefit.

  • @ddhanlin
    @ddhanlin Před 3 lety +6

    Great topic Dave. Reminds me of my first couple of weeks of computer science 101.
    Course Overview - there will be 10 assignments in this course, your final mark will consists of your best 9 assignments.
    Assignment #1 - Create a string library with your own set of common string functions. (So many of my classmates got caught up in frosh week that they skipped the 1st assignment and decided they would work hard on the next 9).
    Assignment #2 - Using YOUR PERSONAL STRING LIBRARY you created from week #1... :) LOL

    • @nickwallette6201
      @nickwallette6201 Před 3 lety

      haha! That's devious. I like it.

    • @ddhanlin
      @ddhanlin Před 3 lety +1

      @@nickwallette6201 Jaws were dropping as students realized they would have to completed Assignment 1 for no marks in order to even attempt Assignment 2. :)

  • @thogameskanaal
    @thogameskanaal Před 2 lety +5

    I love you, just for the fact that you stick with GPL2 licence for your code snippets! You don't wanna know how many people just blindly apply GPL3 to their projects and shoot their future selfs in the foot, especially when they want to use their own projects in proprietary use cases.

  • @unlokia
    @unlokia Před 2 lety +1

    Dave, you are the most charming, eloquent, knowledgeable, kind and endearing, genuinely funny programming savant. I admire you sincerely. God bless you

  • @billsherman6129
    @billsherman6129 Před 2 lety +2

    /W4 is the way to go! At a prior job I was asked to review a program that would periodically crash. 3 other programmers had reviewed it but were unable to find the problem. I set to /W4 and there were 2000 warnings!!! OMG! I went through each line, determined whether the code was safe, and adjusted to avoid the warning. In the end there were 3 lines of code that weren't safe. I adjusted the code to behave correctly. Voila! Success! Do NOT ignore warnings!

  • @AusSkiller
    @AusSkiller Před 3 lety +24

    Here's a good C++ topic: Template meta-programming
    Lots to cover there, could do a whole series on it, there's a lot of useful stuff it can do but most C++ programmers (including myself) aren't too familiar with how to use it effectively, and less experienced C++ programmers basically see it as black magic.

    • @Raspredval1337
      @Raspredval1337 Před 3 lety +2

      but it's just like typesafe macro expansion with some syntactic sugar on top of it tho. And it gets even more typesafe with concepts and the 'requires' keyword

    • @dougpark1025
      @dougpark1025 Před 2 lety +1

      Rule one about temple meta programming is that if you think you need it, you are probably wrong. However, there are a handful of really compelling reasons to use it. Still even on teams with exceptionally smart programmers I have found that few are capable of maintaining templates...

    • @AusSkiller
      @AusSkiller Před 2 lety +5

      @@dougpark1025 I work in games, anything that can be done at compile time is a huge win over something that is done at runtime. Usually we need to have big blocks of comments explaining what the magic values we use are, and checklists for modifying anything they were based off so the magic values don't get outdated. Template meta-programming can solve a lot of those cases at compile time and are generally more powerful than macros which often can't do what we need. Though it definitely isn't something that is needed frequently.

  • @ExSpoonman
    @ExSpoonman Před rokem +2

    "I've been coding C++ for 30 years.....now I'm finally getting good at it" -- Do you know how intimidating this is?!?!

  • @MrJugsstein
    @MrJugsstein Před 3 lety +6

    David thanks for you time Really like you stories packed around so much info ( that it's all above my head doesn't seem to matter) 😊

  • @TravisVroman
    @TravisVroman Před 3 lety +5

    I'm so glad I found your channel. Every video has something in it I didn't know, and I've been writing c for a long time (though not near as long as you)
    Thank you!

  • @RDTengineered
    @RDTengineered Před 3 lety +8

    Net Send!!! I miss that. Sending messages during computer class was fun at the time.

  • @siljamickeify
    @siljamickeify Před 2 lety

    I love when you share mistakes, bad habits, etc. When people with more experience than yourself show how and when they make errors or mistakes, it gives the less experienced person so much valuable context, by which hers/his own body of knowledge can be judged. When the expert never fails at anything, and needs zero time to accomplish comparatively outlandish results, it is detrimental to the experience. But showing the, not always straight to target, path there inspires. Great work!!

  • @lexihaley2887
    @lexihaley2887 Před 3 lety +12

    I just want to say how much I appreciate your content; thank you very much!

  • @masterinsan0
    @masterinsan0 Před 2 lety +2

    Looking forward to more of these! C++ is the first language I learned (aside from some messing around in BASIC) back in 2000, but I haven't kept up to date. You bet my code was full of insecure string functions. These videos are great for helping me modernize my knowledge!

  • @jamesrussell-ui6gd
    @jamesrussell-ui6gd Před rokem +2

    after 30 years im finally getting good at it - dave you should get a netflix comedy special hahahaha

  • @Michael_Brock
    @Michael_Brock Před 3 lety +6

    You finally made C an interesting topic! ♥️♥️♥️♥️ I know a lot of the details went way above my head, but I enjoyed this video 👍👍👍👍

    • @DavesGarage
      @DavesGarage  Před 3 lety +4

      Glad it was helpful! Or at least enjoyable!

  • @rgarciaf071
    @rgarciaf071 Před 3 lety +9

    I'd love to watch an episode about functors, I really enjoy this channel!

  • @AusFin316
    @AusFin316 Před 3 lety +12

    Excellent Dave! Thank you for the wonderful content. After 30 years, you are finally getting good at C and C++ 😁 Gold 👍 I moved to C# instead. Loved the sudden style change of no braces after 30 years. Code style changes are fascinating! I know it just feels right, but why didn't it before? What is your opinion of single line "if" statements? Mine seems to vary. Were you ever subjected to stupid coding standards about such things? My C++ topic suggestion is Templates.

    • @keit99
      @keit99 Před 2 lety

      I know I use single line ifs only for guards if(!valid) return;

  • @siyuanxu5667
    @siyuanxu5667 Před 2 lety +4

    Hi, Dave! I am an IT student. This is my first comment on CZcams. YOU ROCK! The stories you tell are facinating. And the technical informations are brilliant! And you do not even charge any peny. Thanks a lot for your effort!

  • @evanbrito8145
    @evanbrito8145 Před 3 lety +5

    The ellipsis operator/variadic functions would make for another great topic for a video (or a few if you get into templates and parameter packs). Another great common pitfall topic to cover for C++ would be implicit narrowing conversions. It's an area where I think many C++ devs. don't know all the details, and are uncomfortable asking.

  • @timwhitman
    @timwhitman Před 3 lety +1

    Given how many security vulnerabilities there are today... Not enough people read Writing Secure Code...
    Either way, thanks for telling your story. Its amazing to hear all of this wisdom.

  • @i_am_aladeen
    @i_am_aladeen Před 3 lety +62

    I wonder: How old is the oldest line of code that can be found in Windows today?
    Are there any NT-code that are still being used with little to no modifications?

    • @mytech6779
      @mytech6779 Před 2 lety +13

      Yeah the FAT32 disk format tool is from the NT days. He did a video on it. Likely some older than that. But you have a definition problem, for example some C libraries may be very old even older than any windows OS and those could be considered lines of code in windows with little modification.

    • @tawnos1787
      @tawnos1787 Před 2 lety +4

      I remember watching a video a while back about someone taking a very early version of Windows (don't recall the start point, but it was definitely pre-3.1) and running every Windows upgrader in sequence up to the latest version. Each step along the way, they would stop and see what had changed and, more interestingly, what had not. And there were definitely some holdovers from the very early days in there.

    • @srpenguinbr
      @srpenguinbr Před 2 lety +3

      The custom keyboard layout maker doesn't accept file paths with whitespaces or other weird characters, and it seems like this "bug" has been present for a long time. I found some complaints on a 2004 forum.

    • @Bokto1
      @Bokto1 Před 2 lety +3

      I can think of a few things that look like they predate NT. Character picker, Hyperterminal

  • @DividedWeFall
    @DividedWeFall Před 3 lety +3

    Roll out for SP2 went surprisingly well and updating XP rigs payed for many coffees over the years leading upto win7.
    So, Thank you Dave.
    I'd love to see a MS-DOS icon and TaskMan UI enamel pins.

    • @DavesGarage
      @DavesGarage  Před 3 lety +1

      I have a limited run of 100 TaskMan enamel UI pins that I had made. I've given away a few to users that have suggested cool video ideas or caught obscure easter eggs, that sort of thing. But they're pretty rare!

    • @DividedWeFall
      @DividedWeFall Před 3 lety

      @@DavesGarage Well it never hurts to ask so thank you for the speedy reply
      If I order 2 coffee cups the proceeds go to the npo/charity (awesome) however do you ship them directly or that a hands off process so to speak.
      Sorry for the late reply, I'll try not to be a time thief. xD

  • @dingokidneys
    @dingokidneys Před 3 lety +2

    Cool stuff. I managed to write my own printf with a variable argument list back in the late '80's when I had no access to a real C compiler. I was playing with a shareware 16bit C compiler which had no libraries at all and which ran from 1.44MB diskettes as I was using a work laptop with a 20MB hard disk. I was (am) an accountant who just loved computers. I set out to write my own C stdlib to go with it and learned a lot by doing that.

    • @DavesGarage
      @DavesGarage  Před 3 lety

      Great way to learn how it's all really done!

  • @DavidLindes
    @DavidLindes Před 3 lety +1

    warnings as errors, not just silently truncating... yes, yes, yes... nice to see someone else who thinks a bit like me on such things. Great video! Thanks!

  • @grakkal
    @grakkal Před 3 lety +2

    Props for the Atari 830 Accoustic Coupler modem on top of the 850 Interface! Took me a second to realize what I was looking at.

  • @DavidvanDeijk
    @DavidvanDeijk Před 3 lety +1

    Great Video. The /w4 /wx touched my heart. 💖 Hope not too many Devs did blind suppression after it was implemented.

  • @jms019
    @jms019 Před 3 lety +11

    I favour asprintf() for that job as is standard enough, needs little thought and fails in a simple way. More generally just don’t use functions which are still easy to get wrong. That’s what C++ and other languages’ string classes are for

    • @gunkulator1
      @gunkulator1 Před 3 lety +2

      Came here to say this. Given the choice between safe non-standard and safe standard functions, choose the latter. C++'s string class is better at handling strings anyway.

    • @evanwilliams2048
      @evanwilliams2048 Před 3 lety

      In some contexts it's better to avoid heap allocated memory.

    • @climatechangedoesntbargain9140
      @climatechangedoesntbargain9140 Před 3 lety

      @@evanwilliams2048 you can use a custom allocator or use string views

  • @Fetrovsky
    @Fetrovsky Před 3 lety +26

    The recommended way of including standard C headers in C++ is to include instead of , instead of , etc.

    • @DavesGarage
      @DavesGarage  Před 3 lety +38

      Since I was not using any C++ specific features, I kept it C-compatible, for the most part. But when I'm doing C++, I do it the way you indicate!

  • @paulh0029
    @paulh0029 Před 3 lety +2

    I program from the 1980's started with a 1802 in assembler. Then C and even fortran. But I still learn from video's like this. My daugter is now programming in C++ so I have to catch up my skills. It is good to take some time to upgrade your coding skills. Thanks

  • @codewizard58
    @codewizard58 Před rokem

    40+ years ago I learnt C by writing a C compiler in Pascal for the CDC mainframes. Non ASCII, 60 bit words, flat filesystem. Added a cross compiler for 8086 ( segmented memory space ). Started by outputting Forth style stack operations. Sold three or four copies.

  • @driftlessheights6177
    @driftlessheights6177 Před 3 lety +1

    Refreshing. Miss my Kernigan and Ritchie days but I dont remember any of these functions. Nice and understandable.

  • @oneeyedphotographer
    @oneeyedphotographer Před 2 lety

    I programmed for IBM S/370 computers running variants of OS. My main languages for Assembler F (for systems code), COBOL, PL/1.
    In Assembler, I might have had the odd problem with pointers and timing, and I had a couple of spectacular paper eaters. One generated "Intervention required" on a virtual printer. Had the operators confused. I filled VM's printer spool. And there was the paper cutter. The printers used continuous paper, and it was customary to print a line of asterisks on the fold between jobs to make it easy to find them. Print enough lines of asterisks on the same fold line and the paper gets cut. Operators don't like that.
    Since I did interesting new magic things, the operators were generally pretty forgiving. It helped that I was running in a test environment.
    IBM types got to use PL/S and later PL/X similar to PL/1.

  • @shmred5705
    @shmred5705 Před 3 lety

    Hi Dave, thank you for the amazing content. Your sizeof "change" after 30 years really hit me, to me being able to test new styles of coding and not get stuck in "I like it this way" is a sign of a good programmer.

  • @michaelmoltke911
    @michaelmoltke911 Před 3 lety +9

    God darn it.... I'm addicted to this channel

  • @mikelong3444
    @mikelong3444 Před 2 lety

    👍 @Dave'sGarage your content is fantastic these use cases are more advanced than my current skill set. Primarily due to me still being in the introductory phase of my C++/programming journey. Today I was test my knowledge of how to use Composition In C×+ without my textbook. Additionally, I have not used a debugger yet with any my textbook lessons. However, your content is Gold to me. Your content provides value. Thanks.

  • @iraklilomidze5475
    @iraklilomidze5475 Před 3 lety +72

    Dave, you mentioned in your previous episodes that some code you build for Microsoft OS, was non-debuggable. Could you share some ideas on how to make some of our critical code non-debuggable as well? The only idea I get in my mind is to measure code execution time and if it is more than expected, then change code execute flow to mislead the person who is trying to debug.

    • @tomysshadow
      @tomysshadow Před 3 lety +19

      Look up "The Ultimate Anti-Debugging Reference" by Peter Ferrie. It's a bit old now and nothing is completely undefeatable, but it may give you some good ideas.
      For example, one of my favourite techniques is to have the program run itself as a debugger, and have the debugger parent process change the control flow of the child process in a way that is necessary for it to work (have the child throw an exception, parent catch it and set a new thread context, or write to the process memory, etc.) This means you can't attach to the child process (which is the bulk of your program) with a debugger since, there's already a "debugger" attached (which your child process is dependent on to function correctly)

    • @gunner9037
      @gunner9037 Před 3 lety +4

      he's probably talking about code not being debuggable by Visual Studio, so simple checks such as IsDebuggerPresent would work for that. it completely falls apart when you use a third-party open source debugger such as x64dbg which can hide itself

    • @tomysshadow
      @tomysshadow Před 3 lety +2

      @@TheAndreArtus Yeah, I've seen the timing idea used in the wild, but it's not a good anti-debug IMO. Of course, like I said, none of them are undefeatable. They only create a temporary hindrance.
      The reason I don't like the timing idea is that any freeze up or temporary lag spike could trigger the check - and, it's usually not difficult to work around, either. It's a high risk, low reward technique.
      Unless you know how to remove such a protection, you're not really in a position to create one. Modern protections like Denuvo hire hackers to break them on purpose, then continue to revise until they can't be broken (easily) anymore.

    • @robertsentgerath1008
      @robertsentgerath1008 Před 3 lety

      Take a look how cpus cache code ahead. You can write code “assembly” that modifies the next statements executed to distract the person analyzing/debugging the code. If debugged, the flow gets misdirected from the actual cached code execution. If undebugged, the original code executes in the “fast” undebugged and original code execution. Smart debuggers will catch that and just skip those lines to remain on the original path, they might nop out those lines trying to fool those unaware of cpu code caching.

    • @tomysshadow
      @tomysshadow Před 3 lety +1

      @@robertsentgerath1008 Unless I am mistaken, that wouldn't work on x86 at least. Calling FlushInstructionCache, while good practice, is not strictly necessary there. I assume since the OP asked here they're asking about Windows/x86, but I don't doubt it would work on other CPU architectures

  • @chswin
    @chswin Před 3 lety +15

    Would be cool if you talked a little about c++ / c# interop!

    • @DavesGarage
      @DavesGarage  Před 3 lety +9

      Can you tell me what you mean? I do have some stories of how the shell was originally pure C but worked with C++ and COM by manually calling through vtables and such!

    • @perwestermark8920
      @perwestermark8920 Před 3 lety +1

      @@DavesGarage I have still never tried to ha e C call through a C++ virtual method table. Seems I need to set up a weekend project on how to abuse a computer language. 😀

    • @c4ashley
      @c4ashley Před 3 lety +1

      Like calling native code from the .NET framework? PInvoke, Marshaling, [DllImport], all that jazz? I'd be keen for that!

    • @digitalconsciousness
      @digitalconsciousness Před 3 lety +1

      I am just now exploring ImportDLL and the concept of having a static library that is used to load in the dynamic libraries. My code doesn't work quite yet, but getting there.

    • @evanbrito8145
      @evanbrito8145 Před 3 lety +2

      Using C++ CLI for .NET interop. is a great topic. It's still often way cleaner, easier and less bugprone to author interop. libraries in C++ CLI than any other .NET language when wrapping C and C++ libraries. There are lots of interop. layers still out there built this way that can be a challenge to maintain for devs. unfamiliar with this technology. Many great potential pitfall topics to talk about like CPU target architecture dependence for memory alignment and handling callback functions from native code without crashes on app. shutdown in .NET applications as well.

  • @paulschmidt7473
    @paulschmidt7473 Před 2 lety

    I've been playing with C/C++ for nearly 30 years, the first thing in compiling code, is to make sure it compiles clean, no errors, no warnings.... I sometimes see other peoples code, such as some libraries and there are hundreds of warnings in the code..... Warnings are problems in the code, you can spend weeks trying to track down logic bugs, that the compiler actually warned you about.
    For strings on modern computers in C, I like to define them this way:
    char *buff
    .
    .
    .
    buff = (char *)malloc(512);
    memset(buff,0,512);
    I now know that, the data space is zero filled. I've sometimes, memset the buffer multiple times, because I am using is as a string, before freeing at the end.

  • @danidotexe_
    @danidotexe_ Před 3 lety +36

    Hey Dave! Love the content. Just wanted to let you know that you can add timestamps to CZcams videos in the description and it will put them in the video timeline in the player. Super useful for content like this!

    • @peteralund
      @peteralund Před 2 lety +3

      It is considered good practice to include your own examples to show the utility
      1:00 the start
      2:00 another minute
      3:00 etcetera

    • @colinmaharaj
      @colinmaharaj Před 2 lety

      @@peteralund yes, but usually fans do this 'dirty' work for him.. LOL

  • @13Cubed
    @13Cubed Před 3 lety +4

    How about a comparison of how to write a window/GUI-based "Hello, world" in C# vs C++, and which language is more popular for modern development. For those new to Windows development, a quick segment on Visual Studio Community vs Professional vs Code would be nice too -- a "how to get started guide", if you will.

  • @DanielMonteiroNit
    @DanielMonteiroNit Před 3 lety +39

    I'm curious on how the Windows codebase migrated code using far pointers to the flat addressing model

    • @DavesGarage
      @DavesGarage  Před 3 lety +34

      It was all largely rewritten for the Win16->Win32 conversion, but that was done just before I arrived!

    • @iDontProgramInCpp
      @iDontProgramInCpp Před 3 lety +6

      The hell is a far pointer?

    • @1971merlin
      @1971merlin Před 3 lety +9

      @@iDontProgramInCpp in 16 bit x86, a 16 bit segment:16 bit offset address in memory.
      This is generally rearranged into a 20 bit number representing the flat real address in the 1mb address space.
      Regular pointers are within the 64k block relative to the segment value set by the os (com) or specified/assigned after relocation (exe).
      16 bit code in real mode was generally only able to address 64k without far pointers.

    • @iDontProgramInCpp
      @iDontProgramInCpp Před 3 lety +1

      @@1971merlin who thought that using this mess was a good idea?!

    • @DanielMonteiroNit
      @DanielMonteiroNit Před 3 lety +6

      @@iDontProgramInCpp it was a matter of keeping retro compatibility and cost of memory back then pressuring the design, if I'm not mistaken.

  • @samuelclemens6841
    @samuelclemens6841 Před 3 lety +5

    The way that C++ manages exceptions is pretty different from other programming languages. Windows approaches exceptions slightly different from other operating systems too.

  • @theRealRindberg
    @theRealRindberg Před rokem

    It's more than 15 years since I coded in C/C++... OMG I lost it all sadly :( which video proved to me. I remember really disliking (almost hate) C# in the beginning because I felt I lost control, I wanted to manage memory allocation/management my self.

  • @akulkis
    @akulkis Před rokem

    The funny thing about the "don't do security by obscurity" is the fact that ALL security protocols are based on obscurity, whether it's passwords, hardware encryption, the exact shape of the working surface of a physical key, ALL of it is, in some way or another, based on the specifics being hidden from an attacker obscure.
    Sideways attacks don't break the security barriers, they more or less teleport around it.

  • @krigun
    @krigun Před 3 lety +1

    I've read the Scott Meyers "Effective C++" and I really feel that those books made me a better C++ developer, made me understand why to do things in a certain way, and what not to do. But nowdays, I'm not so sure I am that efficient in C++ anymore, new standards, etc. Would be neat to see some small videos on what to do and what not to do in modern C++. Like move operators vs pass by const ref etc.

    • @DavesGarage
      @DavesGarage  Před 3 lety +2

      The Meyer's books are the best, I think. I want to do videos on a few of those topics, as you say, like move semantics and const ref, etc!

  • @boristheengineer5160
    @boristheengineer5160 Před rokem

    For anyone wanting to know what makes a C function hazardous just look up "gets". "It stops when either the newline character is read or when the end-of-file is reached, whichever comes first". That ought to be ammened to add "or when something critical gets overwritten".

  • @Telukin
    @Telukin Před 8 měsíci

    "Now that I'm getting good at it..." - that's the thing - at the time, you think you're great, but when you look back, "Wow, I was bad" - experience really is such an important part of being a good programmer.

  • @tomysshadow
    @tomysshadow Před 3 lety +5

    No touching upon the Unicode counterparts for these functions? (wcslen, wcscpy...) Given, I can't be bothered to use them in my own projects and they're near identical, but they have the same _s implementations so could've been at least briefly mentioned

  • @ryanries09
    @ryanries09 Před 3 lety +3

    pragma warning suppress will disable the warning only for that one line of code. Saves you 2 unnecessary lines of precompiler text pushing and popping

  • @Burgo361
    @Burgo361 Před 2 lety +1

    I miss the fun that could be had with netsend back in the day. I can see why that may have been an issue though haha

  • @orthodoxNPC
    @orthodoxNPC Před 2 lety

    this is awesome
    , the sound effects and animations are all well placed!

  • @streamdx
    @streamdx Před 3 lety +1

    It will be great to see C++ custom allocators

  • @luke12689
    @luke12689 Před 2 lety

    Dave, thanks for the lessons. I use these functions all over from firmware to software.
    I will keep this video next time I need these functions on software.
    Taking me to school by Dave.

  • @AbAb-th5qe
    @AbAb-th5qe Před 3 lety +52

    Microsoft's _s functions are not always available on other C runtimes and recomending them as replacements for unsafe functions like strcpy or strcat is damaging in its own right as the concepts behind them are what's dangerous. Fixed size buffers in general are a poor choice for string handling.

    • @perwestermark8920
      @perwestermark8920 Před 3 lety +18

      Fixed size buffers are often the only correct route.
      But a good choice is:
      strcpy -> res = snprintf(dst,sizeof dst,"%s",src);
      strcat -> res = snprintf(dst,sizeof dst,"%s%s",s1,s2);
      snprintf() is generally available unless in very, very old embedded environments.
      Only bad thing is some old implementations gives wrong return for too small buffer. They return -1 instead of actual size needed.

    • @AbAb-th5qe
      @AbAb-th5qe Před 3 lety

      @@perwestermark8920 yeah snprintf is a more reasonable choice if you have to use fixed length buffers, however most of the time you don't need to. Also, to get the length needed you can call FILE temp = fopen("NUL", "wb"); then size_t len =fprintf(temp, ... that should always return the number of bytes needed (but you'll also need to add 1 to this value for the null string terminator). asprintf if available does all this together with malloc internally

    • @perwestermark8920
      @perwestermark8920 Před 3 lety +14

      @@AbAb-th5qe Many times for embedded, you need to be very, very, very careful about dynamically allocated RAM because the total RAM is so low and fragmentation is no fun in a device that expects uptimes in months or years.

    • @AbAb-th5qe
      @AbAb-th5qe Před 3 lety +2

      @@perwestermark8920 true, but in those kinds of scenarios its better to avoid string handling altogether right? The concept of the heap in C doesn't help matters. You could build a "sliding heap" to prevent heap fragmentation I guess, but that's unnatural to use from C

    • @perwestermark8920
      @perwestermark8920 Před 3 lety +8

      @@AbAb-th5qe Embedded devices normally still need to process communications protocols etc. Just that they often need to focus on static allocations so if they get through the startup code, then they have all memory they will ever need.

  • @VioletGiraffe
    @VioletGiraffe Před 3 lety +3

    Great video as always, thank you, Dave. But for any programmers reading this: please, PLEASE do not EVER throw exceptions of any types not inherited from std::exception! Use std::runtime_error, or std::logic_error, or any other exception type from . Or write your own struct / class, but inherit it from std::exception.

    • @AbAb-th5qe
      @AbAb-th5qe Před 3 lety

      Exceptions are a billion dollar mistake in general. They make reasoning about the state of a processes data extremely hard and are unnecessary for flow of program control. Functions that return error codes can be used to achieve the same effect without complex stack unwinding

    • @nilstrieb
      @nilstrieb Před 3 lety +4

      @@AbAb-th5qe Exceptions aren't great, but random integer error codes are even worse.

    • @DavesGarage
      @DavesGarage  Před 3 lety +13

      I appreciate the input and you're technically correct, but the problem is that you can't really do that in a CZcams video. Now you've lost at least 15,000 people at "WTF if std::exception and std::runtime_error and std::logic_error and why do I need stdexcept? What's a namespace? Why is Dave skipping over all this stuff and not explaining ANY of it????? Why did he write his own struct/class an inherit from std::exception without explaining why he did it? I'm going to watch Amanda McCants programming instead."
      Or, the alternative would be a 45 minute video that no one would finish. Note that I didn't even bite at the apple of "parameter validation with exceptions is a bad idea because malformed input is not truly an exceptional case" and so on. There just isn't time.
      In other words, you can only introduce so many topics at a time and you can't leave loose ends like that. So it's better in a video like this to throw the absolute simplest thing (I would have thrown void, if you could). And then, when I do introduce exceptions, I'll discuss the proper way. But for now, the only point I wanted to cover is "You can use an exception from the handler". The minimal amount of syntactically code to do that is best, at least for the video. Now I regret the negative since, it's longer! Is throwing a negative int a good way to build an exception heirarchy? No. Is it correct? Yup.
      Now you don't want to introduce bad style (which this is), and but you never want to be incorrect (which it isn't). So given the choice of poor style brevity and verbose completeness, in a venue like this you have to go with "shortest correct". Which is why magazines and so on often omit error checking... not to teach that you shouldn't check for errors, but because the space provided doesn't allow for it.
      But as I said, you're right. Exceptions are very hard to get right. Witness how bad it was in MFC and early attempts. I'm not even sure the CRT has it solved. But I know that to this day, I have never been involved in a significant project that was exception based. Everything I've ever worked on that was successful was standard if-else failure code logic. Heck, I even pass std::nothrow and check memory allocs myself! You just can't "dabble" in exceptions.

    • @AbAb-th5qe
      @AbAb-th5qe Před 3 lety +1

      @@DavesGarage Yeah. errno was a terrible idea as well and where error codes are returned by functions in the c standard library there's no consistancy. The toolkit library in mac os classic actually did this fairly well.

    • @mrcrackerist
      @mrcrackerist Před 3 lety

      @@AbAb-th5qe The problem with exceptions/longjmp is that they are slow because of how memory is handle, on the other hand a jump table using if statements are faster and causes less overhead.
      But that being said deepening on what you are programming exceptions/longjmp can be a good alternative.

  • @RideGasGas
    @RideGasGas Před 2 lety

    +1 for Neil Stephenson. Reading Termination Shock now . . .
    An electrical engineer who has been C and C++ programing since the early 80s - first on Mark William's Coherent Unix running on an early IBM PC. Remember well when the _s functions were implemented and required updating my code. Annoying at the time, but appreciated the reasoning behind them.

  • @michaelbauers8800
    @michaelbauers8800 Před 3 lety

    First off, great video. Secondly...wikipedia says you are a master at Tempest. Which is really impressive to me, because that was a really hard game due to having to precisely control that spinner control. I love how youtube introduces us to so many cool people with interesting things to say and teach.

  • @dtikvxcdgjbv7975
    @dtikvxcdgjbv7975 Před rokem

    Keep up with Your excellent work.👍
    I also like Your sense of humor 😂

  • @franciscovarela7127
    @franciscovarela7127 Před rokem

    Good book recommendations, Snow Crash for imagination, Writing Secure Code for the craft.

  • @PaulMJohnson
    @PaulMJohnson Před 3 lety

    I very much enjoyed the history lesson at the start. It was around the XP SP2 release that I jumped ship to Mac. XP had just been too troublesome for me to keep going with it, and it also felt like Apple were bringing new features into the OS at a time XP wasn't really changing from a user point of view - now I know the developers were all working on security at that point.
    It's impressive how far Microsoft have come. I use Win 10 on my gaming rig, and really like it. If I was just a Windows user now, there's absolutely no reason to move to Mac OS that I can see anyway.

  • @m4nc1n1
    @m4nc1n1 Před rokem

    I have a 100TB NAS too (Synology)! Glad I am not the only one, lol. I also have a 36TB NAS (also Synology), a 3TB SSD TrueNAS Core for testing and a 32TB TrueNAS Scale, lol

  • @msx47_
    @msx47_ Před 3 lety

    I love your videos. There's really no one who does stuff like this.

  • @moonasha
    @moonasha Před 11 měsíci

    woah! if you haven't read snow crash you should, it's a modern classic. The main character is a katana wielding pizza delivery man who delivers pizzas for the mafia in an armored sports car. That alone should be enough to make you read it

  • @Nik930714
    @Nik930714 Před 3 lety +2

    I'm currently on a sick leave, since i have some sort of shitty flu. I found your gold mine of a channel and i've been watching it for the last few days. Its amazing. Thank you for the great content in general.
    PS: Video idea - What will be cool is if you compare native M1 ARM code to an x86 app using Rosetta with the prime sieve algorithm. Yes the native code will be faster, but by how much? Or a better question - how good is Rosetta? From what i've read in reviews - pretty damn good.

  • @dsuess
    @dsuess Před 3 lety +6

    Ladies and gentlemen, the man, the myth, the legend... Dave Plummer!

  • @AahhBurnedToast
    @AahhBurnedToast Před 2 lety

    Very informative and a fantastic reminder of why I gave up with C++

  • @clifforddicarlo9178
    @clifforddicarlo9178 Před rokem

    Topic suggestion: Pointer to member function [ptmf] within, say, a Standard Template Library container, such as:
    map myMap { {"-E", ptmf1}, {"-B", ptmf2}, {"-Z", ptmf3}, {"--kay", ptmf4}}; where ptmf1, ptmf2, ptmf3, and ptmf4 all have function prototype signatures like,
    void *(*)(string, int);

  • @2khz
    @2khz Před 2 lety

    Would love a third episode! :)

  • @0dWHOHWb0
    @0dWHOHWb0 Před 3 lety +5

    Why use C-strings inside C++? Just enforce a hard boundary between where you interact with some C API and your C++ program. Ingest C-strings by feeding them into std::string constructors and then bring them back out from string.c_str() if you need to take them back out for the API.

    • @DavesGarage
      @DavesGarage  Před 3 lety +1

      I'm sure you find yourself creating std::strings from C strings all the time, and not just constants. So you have to know how to deal with them, but I'd argue the best thing is to get it encapsulated in a string object as soon as you can trust it. That's sort of my boundary - raw strings untrusted, but string object have been parsed.

    • @0dWHOHWb0
      @0dWHOHWb0 Před 3 lety

      @@DavesGarage In what manner does handling "untrusted" C-strings with functions lifted from C, differ from handing the char* straight to your std::string constructor? If you want to cap the size, for instance, you can just pass it as a second parameter to the constructor. If the C-string could be missing a null terminator you're more or less powerless to do anything else regardless. What I'm saying is there's no need to "trust" things you would feed into the std::string constructor, such that you'd need some additional sanitization steps before then.

    • @TravisFabel
      @TravisFabel Před 3 lety

      ah. just point me to the code you wrote and I'll show you a fun "why" while you reinstall the OS. You're trusting your inputs again.

  • @S0L4RE
    @S0L4RE Před 2 lety

    I’m endlessly happy I found this channel. You explain these concepts so efficiently! Could you possibly make a video on code optimization?

  • @Raspredval1337
    @Raspredval1337 Před 3 lety +3

    I can get the nullptr assertion, but why fire an "exception" when you ran out of buffer space? Like just put a null terminator at the end and return -1 or whatever. It's not that critical to halt the whole program

  • @BalanNarcis
    @BalanNarcis Před 3 lety +5

    I would really like to know the history behind Windows IOCP.

  • @cdrain68
    @cdrain68 Před 3 lety +2

    I do remember the C string functions being a pain as I always got the impression that when you try to make something idiot proof and someone will make a better idiot. I say this after I had some coder who did not use exceptions they used 'shudder' goto

  • @TheGrimravager
    @TheGrimravager Před 3 lety

    10:32
    You are not the hero your team deserved, you are the hero it needed!
    (I don't know if your team deserved you, but you are definitely a hero for that action :D)

  • @tripsix2186
    @tripsix2186 Před rokem

    Have a problem wth Teams turned 90 degrees. Outline is horizontal but image is negative 90 degrees and appears to be in portrait format. This also appears in the Windows Camera app. Wrote a couple apps that could capture image or last image and rotate it 90 degrees but not in stream. Any suggestions? (user has Tiles instead of normal start menu, but tablet settings indicate hardware doesn't support.) Already uninstalled Tiles app.

  • @ac130kz
    @ac130kz Před 3 lety +17

    hands down strcpy, it's like a time bomb in C

  • @rainbain5474
    @rainbain5474 Před rokem

    A lot of my stuff runs behind the scenes in a lot of systems but tends to have a lot built ontop of it. Like a bootloader today where its important you only accept signed code.
    I tend to stay away from libc functions to the point where they're not included at. There, in the past have been a lot of "gotchas" where you think you know how it's implemented but it really does another thing. In general, I avoid 0 terminated strings and pointless and blind memory copies.
    Staying away from them is not going to save you though as some of the worst bugs I have had is from bad pointers. Once had a bug in an event-based system where messing with the registry in weird ways could snag the behaviors of something else in the registry.

  • @skybo053
    @skybo053 Před 3 lety

    Love these informative videos, Dave. Some topics I'd enjoy seeing your take on would be how type erasure objects and operations are working behind the scenes (std::function, std::bind, etc), variadic templates, and threading.

  • @nbooth
    @nbooth Před 4 měsíci

    I'd like to see something on rvalue rederences, designing classes for move semantics, implementing constructors, operator=, etc, automatic memory management and exception safety

  • @rivendzi
    @rivendzi Před rokem

    Thanks for your helpful content.

  • @cedricvillani8502
    @cedricvillani8502 Před 2 lety +1

    Concatenating variables for fun and profit there’s your next video lol oh and did you use fstring?

  • @lucidmoses
    @lucidmoses Před 3 lety

    Your sizeof broke my automatic reading of C more then I expected it would.

  • @airgliderz
    @airgliderz Před 3 lety +1

    Very useful programming best practices. Thank you.

  • @fr5229
    @fr5229 Před 2 lety

    “Now that I’m finally getting good at it…”
    Subbed

  • @modmiiwii
    @modmiiwii Před 3 lety +2

    Thanks dave.

  • @chri-k
    @chri-k Před rokem

    other than causing a callback (and accepting null), how do the strn…_s variants actually differ from the strn… variants

  • @scienceandmathHandle
    @scienceandmathHandle Před 2 lety

    Dave, I know I am a little late the the party, I would love you to go into detail into how to optimize error handling best practices when writing in visual studio. I totally didn't know that trick about calling a separate function instead of the whole abort/retry/ignore window. I don't think anyone at work does either, as I have never seen it before. I use try/catch, but I am not sure what is the proper way of catching say... a hardware error, in say... a serial/tcp/ip return and perhaps returning and logging previously called function calls and other stuff. I only recently learned about the "__func__" macro, which is pretty amazing when it comes to logging. This is more related to debugging rather than production. Great video!

  • @blenderpanzi
    @blenderpanzi Před 3 lety +2

    There is one classic C function that just cannot be used in a save way, but I think it's removed from or at least deprecated in all C libs now: gets()

    • @AbAb-th5qe
      @AbAb-th5qe Před 3 lety

      totally. wasn't gets defined to be implementable as a macro?

  • @colinmaharaj
    @colinmaharaj Před 2 lety

    6:10 I made my own strncat function where you must supply the max len of the final string.

  • @tonibaker8288
    @tonibaker8288 Před 3 lety

    Very valuable advice! Thx for the great explanation!