Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror
×
Programming IT Technology

Secure, Efficient and Easy C programming 357

cras writes "Feeling a bit of masochist today.. First in the morning I wrote Secure, Efficient and Easy C Programming Mini-HOWTO. And since I already spent a few hours with it, I figured I might just as well see what Slashdot people would think about it."
This discussion has been archived. No new comments can be posted.

Secure, Efficient and Easy C programming

Comments Filter:
  • by Anonymous Coward on Sunday December 08, 2002 @02:19PM (#4838329)
    Pick any two.
    • This looks like a good idea for a lib (or more) that covers those issues. It might be already exists, but it's not very well known. (To beginners)

      The other problem is that security issues usually aren't mentioned in general programming tutorials (and books).
      If beginners would be pointed to techniques like this (with explanations why) lots of typical mistakes would not happens.

      --
      Stefan

      Looking for Developers, new project members, testers or help? Want to provide your abilities ?
      DevCounter ( http://devcounter.berlios.de/ [berlios.de] )
      An open, free & independent developer pool.
  • by napoleonin ( 548802 ) on Sunday December 08, 2002 @02:23PM (#4838351)
    "First in the morning I wrote Secure, Efficient and Easy C Programming Mini-HOWTO..."

    Damn. What are your plans for the rest of the day?
  • by Loki_1929 ( 550940 ) on Sunday December 08, 2002 @02:25PM (#4838359) Journal
    "First in the morning I wrote"

    So did you wake up early this morning, or are you still up from the night before, like me?

  • a little short?? (Score:4, Interesting)

    by AmigaAvenger ( 210519 ) on Sunday December 08, 2002 @02:26PM (#4838367) Journal
    I think this might be a little bit too soon to have it posted on slashdot, you only have a few pages covering memory and string handling, and nothing ground breaking at that.

    It does look like a good start, add a few more chapters and you will be halfway there...

    • Re:a little short?? (Score:5, Informative)

      by cras ( 91254 ) on Sunday December 08, 2002 @02:30PM (#4838393) Homepage
      It does look like a good start, add a few more chapters and you will be halfway there...

      Sorry, but I think this is about all I have to say. Secure Programming HOWTO [dwheeler.com] should take care of the rest.

      • Decent -- this is the sort of info I can use. I'm trying to teach myself C without having to un-learn bad habits, so it helps to see the kind of things I should look out for. Where do you plan to post it when you consider it done? The LDP? I'll go grab a copy, thanks!

        BTW the "s" in Sunday should be capitalized (the part where you mentioned "Sunday morning".

        Sorry about that (former English major)
        • Impossible. C, itself, is a bad habit.
          • Impossible. C, itself, is a bad habit.

            Damn true, using C for other thing than low-level stuff really is a bad habit.
            • Yep. It's not a bad, somewhat portable, structured assembler but is just as dangerous as assembler and shouldn't be used where you wouldn't use assembler.
            • Damn true, using C for other thing than low-level stuff really is a bad habit.

              Oh, God, another Visual Basic user who writes code with a mouse. Spare me.

              • by dvdeug ( 5033 ) <dvdeug@@@email...ro> on Sunday December 08, 2002 @08:08PM (#4840646)
                Damn true, using C for other thing than low-level stuff really is a bad habit.

                Oh, God, another Visual Basic user who writes code with a mouse. Spare me.

                Yes, because it's better to spend weeks and months carefully constructing a GUI by hand then to put it together in a couple days with a mouse. Especially if it's going to be used by three or four people; by God, it's more than worth it to the company for me to spend two or three months on the project (@ $60,000 a year) so those people can get their results back in a couple seconds rather than a couple minutes.

                It's also better to spend weeks and months writing an efficent text processing program in C and worrying about buffer overflows and memory leaks, rather then writting it in a couple days in Perl or Snobol. Who cares that the results will inevitably be piped to less and studied for a few minutes; the fact that we shaved off 40% of 2 seconds (and added an obscure error case) is more than worth it!

                Actually: Oh, God, another C programmer that will make me suffer through anonymous core dumps because his programming language is so much more macho, and so much more efficent (really wish he understand how to use Big-O notation and switch algorithms, but he spent so much time programming this one and dubugging it that he can't afford to switch. Too bad he doesn't use a language with efficent control structures predebugged and optimized.)
                • Did I sense irony? :-)

                  But my infinite loops runs *so* fast!

                  And what would I do without my precious core dumps?

                  I can't trust the computer to manage his memory!

                  Who cares about algorithms if the language is fast?

                  I could not live without '\0' delimited strings!

                  Strong typing sucks. Dynamic typing sucks. I like my types to have no purpose other than sizing the fields in memory.

                  Error control and safety are for wimps.

                  Macros should be dumb text substitution tools.
    • Re:a little short?? (Score:4, Interesting)

      by crimsun ( 4771 ) <crimsun AT ubuntu DOT com> on Sunday December 08, 2002 @02:35PM (#4838416) Homepage
      I agree that it's a good start. I would also add in links to vsftpd's design & implementation documentation; see here [beasts.org], here [beasts.org], and here [beasts.org]. For what it's worth, Maradns's [maradns.org] string library is worth examining as well.
  • 1) Use python with C bindings

  • by tuxlove ( 316502 ) on Sunday December 08, 2002 @02:27PM (#4838379)
    It's kind of funny how this guy voluntarily slashdotted himself by submitting an article with a link to his own site, crashing it instantly. :)
    • NOTE: This is a temporary location for this document, selected with slashdot people specifically in mind.

      I think he already planned for it. Seems to be holding up.
    • by cras ( 91254 )
      Well, I didn't link it to original site, but from the look of this so called slashdot effect I think I just as well might have. Come on, I don't see any kind of load at all!

      [cras@foo] ~$ ps ax|grep apache|wc -l
      60

      [cras@foo] ~$ uptime
      20:32:54 up 127 days, 10:58, 56 users, load average: 0.23, 0.41, 0.37

      Those loads were pretty much the same before slashdotting.
      • by Anonymous Coward
        I think Slashdotting only really happens to sites with dynamic content or to sites with a topic more people care about. Oh yeah, and also sites that run on a calculator powered by a potato.
      • The subject will keep most slashbots away. If you had written a howto on securing IE, then you'd get a slashdotting. :)
  • Unportable? (Score:5, Interesting)

    by Anonymous Coward on Sunday December 08, 2002 @02:28PM (#4838384)
    I found strlcat and strlcpy easily ported - simply toss them in the same .c file and dump it into the makefile!

    On a more serious note, why in Bob's name don't these two functions exist, standard, in Linux? IMO, they should be added, and gcc should give deprecation warnings about the use of non-safe buffer handling functions - sprintf, strcat, strcpy, etc. No offense to purists, but screw the standard. I'll sacrifice some portability of software and such for security.

    Oh, and on a side note, you may take my malloc() when you pry it from my cold dead fingers. ;) Eh, I suppose we all have a certain way of doing things that we don't wish to part with. (*points at the unsafe buffer people*)
    • STRLCPY(3) FreeBSD Library Functions Manual STRLCPY(3)

      NAME
      strlcpy, strlcat - size-bounded string copying and concatenation

      LIBRARY
      Standard C Library (libc, -lc)

      SYNOPSIS
      #include <string.h>

      size_t
      strlcpy(char *dst, const char *src, size_t size);

      size_t
      strlcat(char *dst, const char *src, size_t size);
  • Definitely useful (Score:5, Interesting)

    by ttfkam ( 37064 ) on Sunday December 08, 2002 @02:32PM (#4838400) Homepage Journal
    in that folks who use C can avoid common pitfalls. But so much of this seems like it has been tackled by C++. Only C++ did it cleaner. C++ is complex though. So this only leaves (horrors) a higher level language that removes all of these implementation details that lead to insecure programs.

    Do it in a higher-level language first. Make sure your algorithms are clean and efficient. If and only if you see a performance or resource problem do you rework portions(!!!) in C. As a bonus, the higher level language acts as a code template for faster C development.

    Once you are at that point, this Mini-HOWTO will definitely be a great resource to use.
    • by Kragg ( 300602 ) on Sunday December 08, 2002 @03:16PM (#4838635) Journal
      Wow. This is one of the few genuinely insightful comments I've come across.

      Prototyping in a higher-level language (c# is easy, java everyone knows) is a superb idea, provided you
      - can release the final product as interpreted, with slow execution speed
      - can afford the time to port all to C, in which case DO, this is an excellent way to make a watertight C program
      - are happy to learn how to make managed code/vm code call to native and vice-versa (this is far from a trivial problem)

      There are apps that fit into all 3 categories, and if your end-result should be a watertight C program, it may even be faster to prototype.

      Fight the conventional wisdom! make good code by doing it right, not by being a genius who can hold 4000 variables in his mind over a month-long project (because you aren't one anyway).
      • I've worked on large projects and this approach has worked just fine. The basic idea is not to write the entire program in the higher level language but rather to use this language as the glue for calls to functions in lower level languages.

        As a RL example a project I worked on used TCL as the glue for C TUXEDO services and Oracle. So to adress your points above WRT this project:

        1)There were no performance issues in the delivered product, if a part of the code is under performing in the glue language you rewrite it in C and bind to it instead.
        2)We did not need to port all the code to C, identify the small portions of code which benefit greatly from a port and port only them. The time saved here is enormous compared to implementing the entire project in C.
        3)calling to native code in TCL was trivial, if it's "far from trivial" for you perhaps you chose the wrong language for the glue. A popular language for doing this today is Python, in which it is also straightforward to create bindings for.
        • glue != prototype. (in fact, it's E210: invalid type comparison, cannot compare apples and oranges.

          Yes, glue languages are designed to interoperate easily, but I defy you to create a full-blown app prototype in TCL.

          Go on, let's see it.
          • glue != prototype. (in fact, it's E210: invalid type comparison, cannot compare apples and oranges.


            I'm tired of this constant discrimination against the citrus fuits. One of these days the people will get up and say "I'm tired of people thinking that oranges aren't good enough for comparison." They'll say "I can compare apples and oranges". They'll run to the windows and say "This orange is much yellower than this apple". People will be running through the streets screaming "This apple is much more smooth than this orange."

            And then my group(The People for the Ethical treatment of Cirtrus (PETC)) will be happy.
      • You are just picking the wrong higher level languages. There are much better choices, though which is best depends on your problem.

        If you are dealing with highly dynamic data, lots of strings, etc. Start in Python. Then locate bottlenecks and convert those sections to C.

        If you are dealing with a large application, that you need to control precisely, start with Ada. You probably won't need C at all, but be prepared for a lot of work. If you need to call libraries written in C, you can do so realtively directly.

        If you are dealing with a relatively complex application that needs garbage collection, Eiffel is a good choice. Links to C are easy, once you master them, but links back are... dubious.

        If you are dealing with something simple, or if everyone else is using C, then your best choice may be to just use C. (Eiffel can generate C code, but don't expect to be able to read it.)

        I don't like C for anything that isn't REALLY simple. But it's a lot better than the language I've ended up using most of the time recently (Visual Basic). (Currently I think I may have managed an escape from MSAccess into Java. [Wouldn't you know it! I need to learn a new language to escape from one of the worst environments on the planet. But Java is the only choice that mgmt. will accept.])
        • I have no experience with Python - I'm withholding judgement till the cheerleaders quiet down a bit and i can find a sensible description of it's strengths and weaknesses (links anyone?).

          However, as for GC etc using Eiffel - you say links to C are easy once you master them - same with every other language, including c# and java.

          Especially if you're trying to get away from VB, why not use .NET? It may be the beast's but it is still easy and (almost) portable code. And there are a million guides out there on porting VB6 -> VB.NET. Tell mgmt they're wrong.
      • Re:Definitely useful (Score:5, Interesting)

        by hobuddy ( 253368 ) on Sunday December 08, 2002 @04:45PM (#4839328)
        ttfkam wrote:
        Do it in a higher-level language first. Make sure your algorithms are clean and efficient. If and only if you see a performance or resource problem do you rework portions(!!!) in C. As a bonus, the higher level language acts as a code template for faster C development.

        Amen.

        Kragg wrote (in his reply to ttfkam):
        Prototyping in a higher-level language (c# is easy, java everyone knows) is a superb idea, provided you
        - can release the final product as interpreted, with slow execution speed


        Most programs spend 90% of their CPU time executing 10% of their code. If that 10% is optimized in a low-level language such as C, a large-scale interpreted program can boast performance that's virtually indistinguishable from an equivalent program written entirely in a low-level langauge. However, there's likely to be a huge difference in programmer productivity.

        As a reference, see this Dr. Dobbs article [ercb.com], which states:
        """ ... 90 percent of the software's running time occurs in only 10 percent of the code. This is the whole basis for virtual memory: Potentially, a program can run at full speed with only 10 percent of itself--or whatever the working set is--loaded into memory at any given time. Unlike that nasty segment stuff, the programmer does not specify any of this in advance. The operating system "discovers" a program's working set on-the-fly, through page faults.
        """

        - can afford the time to port all to C, in which case DO, this is an excellent way to make a watertight C program

        Why port 90% of the application's code to a low-level and less productive programming language, when that 90% will inevitably evolve and require maintenance as the program is utilized in unforeseen ways? I've never written a large program that didn't end up having features added incrementally over a long period of time after the initial release.

        - are happy to learn how to make managed code/vm code call to native and vice-versa (this is far from a trivial problem)

        If it's "far from a trivial problem", you're using the wrong tool.

        Take Python, for example: it's simple to interface between Python and C using Python's C API [python.org]. Recently, a tool named Pyrex [canterbury.ac.nz] has appeared that makes it almost trivial. Pyrex is amazing.

        Kragg suggested prototyping in C# or Java, but Python surpasses both of those as a prototyping tool. Python is higher-level than C# or Java (and thus better suited to prototyping and/or malleable fusion with C) because it features:
        - dynamic typing ("dynamic", not "weak" like Perl)
        - no obession with a particular programming paradigm; use procedural, functional, or OO as appropriate
        - high-level data structures built into the language
        - more convenient dynamic code loading
        - interactive development at a "Python prompt" (the value of this cannot be overestimated)
        - no separate compilation step in the edit-test-debug cycle
        - more concise syntax
        - excellent interface capabilities to C (or C++ via Boost.Python [boost.org], or Java via Jython [jython.org])

        I suggest that the fusion of a truly high-level (higher than Java-level) language with C is far more broadly applicable than Kragg claims.
      • by denshi ( 173594 ) <toddg@math.utexas.edu> on Sunday December 08, 2002 @06:33PM (#4840094) Homepage Journal
        Prototyping in a higher-level language (c# is easy, java everyone knows) is a superb idea, provided you
        - can release the final product as interpreted, with slow execution speed
        - can afford the time to port all to C, in which case DO, this is an excellent way to make a watertight C program
        Sir! I wish to introduce to you to the strange new-fangled notion of compiled high-level languages! Yes, languages with higher-than-C-level abstractions have been sneakily producing native machine code for some time now. Some of the most popular are listed below:

        • O'Caml is a marvel of strongly typed object orientation, but you'd hardly know it from using it -- there are almost no C-style type declarations; as a ML child, O'Caml uses type inferencing to prove powerful assertions about program validity and improve programmer convenience. It's compiled! And if you watch the ICFP's, you might note that it consistently beats C compilers for speed of execution. '92, if I recall.
        • I never really bought OO, so S/ML is fine by me. Still compiled, since 1984.
        • And they both descend from ML, started in 1973.
        • Lisp was compiled in 59 or 62 (mccarthy or 1.5, chose your valid date). But then, I suppose it'd have to be compiled, since the notion of interpreted code hadn't been concieved of yet!
        • Erlang is the last, best, word in concurrent programming. If you want to write a high throughput, reliable threaded application, you shouldn't even think of the word 'C'. This broke out of its lab in '87, first compiler in '91.
        • Scheme is often thought of as a testbed for interpreted language concepts, but even it can be compiled, and with concepts such as continuations that can actually make a C programmer's head explode! Since 1982, commercial grade compilers have been available.
        • Even haskell is compiled, but as monadic programming is less than 10 years old, no one knows how to always write really fast code in it yet. Leave your number, we'll call you in 2034, right before you gear up to deal with your year 2038 rollover crisis.
        Welcome to the late 1970's! We look forward to your eventual arrival in the 80's and early 90's. Please enjoy your stay!

        ps. As modern coding is more about the manipulation of very complex structures, rather than how to say, walk a linked list; a higher level language, with native support for more complex constructs, has the potential for creating much faster applications than something on the level of C. The reason being is that the h/l compiler can reason about, and thus optimize over, larger components than the C compiler.

  • Wha??? (Score:5, Funny)

    by dirkdidit ( 550955 ) on Sunday December 08, 2002 @02:33PM (#4838403) Homepage
    Secure, Efficient and Easy C programming

    Wait a second. It's not April 1st is it?
  • Lacking some focus (Score:5, Interesting)

    by JimTheta ( 115513 ) on Sunday December 08, 2002 @02:36PM (#4838420) Homepage

    I skimmed over it, and it is a little rough. My main impression is that I'm not sure what I'm supposed to get out of it (wait! keep reading!).

    Who's this meant for? Beginning C coders? Intermediate C coders? Where do C++ junkies fit in? My university taught me C++. I really don't like plain C (feels like coding with some fingers cut off), but I know I need to know it. I was wondering if this would point out some things about C that I ought to know. While I'm sure that it might, I think I might need a beginner's guide first, as a lot of the classic C commands aren't second-nature to me.

    Also, you have a bunch of "The old way" sections. What are these sections telling us? Is "the old way" bad? Do they have their uses? You don't really say. I'm not sure what I'm supposed to get from them.

    It's pretty ambitious for a Sunday morning, and it's pretty good. But you should probably clarify your who your target audience is. Also, look back at each passage; what is the message? Does it put that message across effectively?

    -Grant

    • by cras ( 91254 )
      Who's this meant for? Beginning C coders? Intermediate C coders? Where do C++ junkies fit in?

      It doesn't really fit to C++ programmers, they seem to have better ways to handle things. It's mostly about alternative (IMHO much better) ways to handle the traditional C buffer overflows. I'm assuming the reader already knows C quite well.

      Also, you have a bunch of "The old way" sections. What are these sections telling us? Is "the old way" bad? Do they have their uses? You don't really say. I'm not sure what I'm supposed to get from them.

      They're just the old ways. Not necessarily good or bad. Possibly good sometimes, possibly not. I'm just mentioning another way which I find better in most cases.

  • by webprogrammer ( 518832 ) on Sunday December 08, 2002 @02:37PM (#4838427) Homepage

    From the mini-howto:

    ...I'm not too good at english, so sorry about all the spelling and grammar errors :)...

    From the post:

    Feeling a bit of masochist today...

    Whoa, man.

  • data stacks (Score:5, Interesting)

    by larry bagina ( 561269 ) on Sunday December 08, 2002 @02:38PM (#4838438) Journal
    What I haven't yet seen used anywhere outside my own software and some programming languages internals (eg. calling Perl code from C), is using data stack for temporary memory allocations. It has the most important advantage of garbage collectors; allocate memory without worrying about freeing it. It also has a few gotchas, but I'd say it's advantages are well worth it.

    The way it works is simply letting the programmer define the stack frames. All memory allocated within the frame are freed at once when the frame ends. This works best with programs running in some event loop so you don't have to worry about the stack frames too much. Here's an example program:

    That sounds a little like the NSAutoReleasePool in Cocoa/OpenStep. Objects use reference counting, when the count reaches 0, they deallocate themselves. When an object is created, it can get added to the most recent pool. When the pool is deleted, it decrements the reference count of all the objects within it, causing deallocation unless it needs to be kept around longer.

    • Well, not quite. An NSAutoReleasePool does not allocate a large region of memory and suballocate objects out of that. What an NSAutoReleasePool does is make it possible to avoid explicitly sending the release message for temporary objects.

      For example, from Foo() I allocate an NSObject with [[NSObject alloc] init] and pass that as an argument to Bar() which takes ownership of it. However, I must then ensure that I release the object because Bar() is following good coding practices and retains it, so thus with alloc+retain it's reference count is now 2. So instead what I do is Bar([[[NSObject alloc] init] autorelease]) which allocates NSOjbect (with ref count one) initializes it, marks it for autorelease, and passes sends it to Bar() which retains it (ref count 2) and keeps a pointer to it (presumably it is a method of a class). Coming out of bar the ref count is now 2, and perhaps Foo() proceeds to do some other things. Presumably at some point higher up the call stack (or perhaps at the beginning of Foo()) an NSAutoReleasePool was allocated. At the corresponding exit point (either at the end of Foo() or the end of whatever higher up function) [whateverpool release] will be called. When the pool is released, it will call release on any objects it has been asked to take ownership of. At this point one of two things it true. Either the class that Bar() belongs to has already released the object and thus its reference count went back down to one, and now is going to zero (so bye-bye), or the class that Bar() belongs to has not released the object and doing this release merely brings the refcount back to one such that when the other owner releases the object, its refconut will be zero and it will be freed.

      Sorry if that was confusing, but in reality it's really not. It also really helps out when you are coding functions that allocate ObjectA, then allocate ObjectB, then ObjectC, and then find out something is wrong and need to "roll back" to the begining. If you allocate an NSAutoReleasePool at the beginning, and autorelease everything you alloc then if you error out you can free the release pool and everything gets released. If you don't you can simply retain what you need and then free the autorelease pool.

      Anyway.. what this guy is REALLY talking about is NSZone. NSZone allocates a chunk of memory which other objects will be allocated from. The caveat being that while the memory will be freed, the objects will not be properly destroyed. Now this guy was talking about holding C strings and the like, so this is not a problem. However, had he been holding some C++ or objective-C objects this would be a problem as none of the destructors/deallocators would ever be called.

      I think what it all boils down to is that programmers need to read more code than they write and that we should really be getting Masters of Fine Arts in Programming [slashdot.org]. I completely agreed with what Dr. Gabriel said. Programming is about as much like building a bridge as writing poetry is. That is to say.. not much.

      Going along with that thought, I think it should be pointed out that /EVERYONE/ here who programs in any language (but specifically C programmers, and ESPECIALLY C++ coders) needs to learn Cocoa and Objective-C. I imagine some of the C++ whiny bitches are going to continue to whine about how much easier and better C++ is, but for those of us who actually prefer to wrangle pointers, Objective-C is where it's at. It's like C with JUST enough object orientation, but not overdone in some committee like C++. Also, one should note that I do like C++ quite a bit, but sometimes there's too many provided ways to do things. With Objective-C, the provided ways are almost all good. In addition, like C or C++ you are not limited to doing it that way, it's just that Objective-C only makes it easy to do good things.

      Think for example of wxWindows [wxwindows.org] vs. Microsoft MFC. wxWindows is suprisingly similar to Cocoa (although wxWindows does not do ref counting so making sure that one and only one class ever owns an object can be problematic at times). MFC, on the other hand, is rather a bear to work with as Microsoft has written it such that an MFC programmer /can/ do things multiple ways, none of which work very well. Obviously this is a generalization, but I think the average MFC programmer will understand where I'm coming from here. That is, again, except for the whiny C++ and MFC bitches who can't figure pointers out. Go home!

    • reference counting (Score:4, Informative)

      by ttfkam ( 37064 ) on Sunday December 08, 2002 @03:53PM (#4838918) Homepage Journal
      The main problems with it versus broader garbage collection schemes are circular references and overhead.

      If two (or more) objects have a reference to one another, the count can never reach zero even if nothing in the main logic points to those objects anymore.

      Also, every time an object gains or loses a reference, a check for a count of zero is made. In fuller garbage collection setups, periodic checks are made to all of the objects in a low-priority thread. In some cases, memory usage can be higher, but performance is also higher sometimes and it can handle circular references.

      Both are better than repeated use of malloc/free and new/delete though.

      --

      C also muddies this concept because there are no objects in C.
    • Re:data stacks (Score:2, Interesting)

      by Handyman ( 97520 )
      I've seen an especially nice version of these dynamic stack frames in Cyclone [att.com]. For those of you who don't know it, Cyclone is kind of a type-safe, pointer-safe version of C, mixed with some good features found in languages like ML. It takes only simple transformations to compile C code as Cyclone (mostly having to do with minor pointer syntax differences).

      Cyclone has region-based memory protection, which means that you can't do stuff like return pointers to local variables etc. because it statically checks the pointer lifetime using region tags that are part of the pointer type. Example: you can have a pointer-to-memory-belonging-to-region-foo, where foo is a function or some other static scope, (written sometype * `foo, although the default region tag is usually correct, then it's just sometype *) which can point to heap memory because that's garbage-collected and guaranteed to live at least as long as function foo's memory, but you can't have a pointer-to-memory-belonging-to-region-Heap pointing to a variable on the local stack: if you have a local variable x and take the address, the type of that is pointer-to-memory-in-region-foo, and that type is not allowed to be cast to pointer-to-memory-in-region-Heap because foo's memory doesn't necessarily live as long as Heap does.

      They combined this region-based mechanism with dynamic "stack frames": You can open a dynamic region to open up a new "stack frame" or separate heap of memory bound to a scope in the program, so when an exception is thrown or when you exit the scope the memory is automatically deallocated. The good thing is, you can't go wrong, because the region-based pointer lifetime checking will prohibit you from casting a pointer into that specific region to a pointer into a region with a longer lifetime, so you will never have dangling pointers into such a dynamic region: you will get a compile-time error when you attempt to do this.
  • by dagg ( 153577 ) on Sunday December 08, 2002 @02:41PM (#4838459) Journal
    I'm not a writer and I'm not too good at english, so sorry about all the spelling and grammar errors :) All of this stuff was written at sunday morning, tired after being awake the whole night and not being able to do anything useful...

    I'm going to start putting that at the end of everything I write so that people can't criticize anything I do. As a matter of fact... I think I'll only write on Sunday mornings after not sleeping the night before. It seems like it's always Sunday morning anyways.

    --
  • by PaddyM ( 45763 ) on Sunday December 08, 2002 @02:43PM (#4838472) Homepage
    But I can't follow this HOWTO very well. Does he have a global variable stored in the file with t_push and t_pop so that t_sprintf can use that variable? But if he has a global variable, than all he's really doing is allocating the maximum amount of memory his program will ever need at the beginning, and managing his memory.

    Perhaps working until 4 in the morning on C code has drained my ability to understand.
    • Think about stack and how that works. t_push() and t_pop() basically create and destroy a stack frame, just like your control stack does at the beginning and end of function. So sure it needs to use some global memory for it (not in global variable though), just like control stack does. t_sprintf() simply returns a pointer inside the stack frame.
  • masochist (Score:2, Funny)

    by mike77 ( 519751 )
    Feeling a bit of masochist today...

    You must be to ask slashdot's opinion of your toils!

  • Is this news? (Score:5, Insightful)

    by mthed ( 120041 ) on Sunday December 08, 2002 @02:45PM (#4838485) Homepage
    Some guy spent a couple of hours writing a first draft of a Howto. Thanks Slashdot, I'm sure glad you didn't let this one slip through the cracks! Besides, who cares about these kludgy ways of handling memory. If you don't wan't to worry about memory allocation use C# or java or something. Otherwise, stop eating quiche and write solid code.
  • stack allocation?? (Score:5, Informative)

    by hanwen ( 8589 ) on Sunday December 08, 2002 @02:47PM (#4838496) Homepage Journal
    (yawn)

    it starts off with denouncing GC as oldfashioned, and then proceeds to tout stack-based allocation, which has been available for ages as the alloca() function (which also has portability problems.)

    imho, you should use the Boehm Garbage collector [hp.com], unless you have code that must be guaranteed to be free of space leaks.

  • You Forgot: (Score:5, Funny)

    by asv108 ( 141455 ) <asv@@@ivoss...com> on Sunday December 08, 2002 @02:48PM (#4838508) Homepage Journal
    You forgot to add the obligatory "in XX days" or "XX hours" to your title. So a better title for this story would be:

    "Secure, Efficient and Easy C programming in 24hrs"

  • by Alejo ( 69447 ) <alejos1@h o t m a il.com> on Sunday December 08, 2002 @02:52PM (#4838526)
    Did you really read the strncpy [openbsd.org] and strncat [openbsd.org] manpages?
    To both zero-terminate and check for truncation is arcane, that's why the OpenBSD ppl made strlcat [openbsd.org] and strlcpy [openbsd.org] in the first place.
    There are already other secure programming faqs, though AFAIR, they suck too. If I were you, I'd put a HUGE disclaimer to take this page as work-in-progress.
    (before flaming, write down the correct code to check for truncation for both funcs)
    • Truncating string copies are always wrong, no matter whether you use them correctly.

      What if the result would be bigger than the output buffer? strncat() does the "right" thing, and doesn't overflow the buffer. But your string just got truncated! That's probably bad. So, suppose you check for this problem, by examining the string lengths beforehand. You verify that the result will fit, and not be truncated.

      But now that you've gone to that trouble, and you know that the result will fit, why bother with the strncat()? Since you already know there is no overflow, you can go ahead and use the (faster) function strcat().

      Now, in order to avoid these problems, you might write your own string concatenation function, that first computes the total size needed for the result, allocates it, and then copies the strings into this new buffer. Now, the issue of buffer ownership comes up, and you introduce a new class of possible bugs: memory leaks.

      The fact is, in any non-garbage-collected language like C, string handling is a pain in the ass. The problem runs deep, and can't be solved by any quick hack like strlcat().

  • Devils' Advocate (Score:4, Interesting)

    by windex ( 92715 ) on Sunday December 08, 2002 @02:58PM (#4838564) Homepage
    Okay, let's preface. This guy has a good idea in the memory allocation department.

    Problem 1:

    It's not easy, nor fast to write. Errors are severe if present and undetected. Code required to be reliable might not be a good place to test this allocation method.

    Problem 2:

    I'm not entirely sure these concepts are very portible outside of GCC. May not be a big deal to most, but uh, multiplatform code is required in some enviroments.

    Problem 3:

    Any speed increase without massive resource wasting is pure dumb luck during heavy usage, unless used in an application that takes little user input or has limits on the ammount of input.

    Just my $0.02.
  • by pclminion ( 145572 ) on Sunday December 08, 2002 @03:01PM (#4838577)
    It's a good start at a HOWTO, but needs some serious fleshing out. These are common tricks that most serious, experienced C programmers have in their bag.

    Some of my personal favorites include:

    • Exceptions in C. You can get quite natural-looking exception handling in C, with some convoluted macros. I'm sure most hardcore C coders have come up with their own implementations. Many security bugs happen in parts of the code that handle errors, precisely because errors are rare, and those parts of the code don't get tested well. Using a unified, exception-driven approach to error handling can cut down the risks. IF you do it right.
    • The alloca() function. This allocates memory directly off the stack, which is freed when the function returns. Very useful for cases where you want a stack buffer but aren't sure how big it needs to be. Like any other stack buffer, you need to take care not to overflow it. There are portability concerns with this function, but it can still be useful.
    • Variable-sized block-chained allocators, which pull chunks of memory out of preallocated segments. The segments are chained together in a linked list. Very effective when you need to make a lot of variable-sized allocations, and do it fast, dammit. It also makes freeing the allocated memory blazingly fast, although it's a "free all or none" approach.
    • "Hardened" allocators, which allocate blocks in multiples of the page size, and set memory protections in such a way that buffer overruns cause crashes. This is the easiest way to prevent ANY kind of buffer overrun vulnerability, but wastes memory. See Electric Fence [perens.com].
    Look people.. It takes a keen eye and major discipline to write secure C code. It is not impossible. You have to get in the habit of subconsciously checking yourself at EVERY turn. "Am I accessing a stack variable? Am I doing it CORRECTLY?"

    DISCIPLINE, DISCPLINE, DISCIPLINE. I fully expect to see the usual barrage of comments to the tune of: "C is outdated, insecure, brittle, yadda yadda..." No. Some PROGRAMMERS are "outdated, insecure, and brittle."

    The C language doesn't write bugs. Programmers write bugs. If the programmer can't handle C, then take it away from him. But don't try to take it away from ME.

    • DISCIPLINE, DISCPLINE, DISCIPLINE. I fully expect to see the usual barrage of comments to the tune of: "C is outdated, insecure, brittle, yadda yadda..." No. Some PROGRAMMERS are "outdated, insecure, and brittle."

      The moral is to always use the right tool for the right job. You wouldn't use a chainsaw to do heart surgery and you wouldn't fly a 747 to travel 30 miles.

      C is really good at certain things, but writing secure code isn't really one of them: meaning that you have to go through some extra effort to ensure your C code is secure. If you can solve your problem in another language with less effort and that language meets all your requirements (speed, memory use, portability, whatever else), then why pick C in that case? Not every application requires maximum speed or easy bit twiddling.

      The C language doesn't write bugs. Programmers write bugs. If the programmer can't handle C, then take it away from him. But don't try to take it away from ME.

      Nobody's advocating take C away. But you shouldn't be slavishly devoted to it as the One True Language. You should choose the language that will allow you to solve your problem with the minimum amount of effort, taking into account whatever constraints are relevant.
    • Variable-sized block-chained allocators, which pull chunks of memory out of preallocated segments. The segments are chained together in a linked list. Very effective when you need to make a lot of variable-sized allocations, and do it fast, dammit. It also makes freeing the allocated memory blazingly fast, although it's a "free all or none" approach.

      Not necessarily - depends how you implement it. For example, the SmartHeap library would use fixed size allocators for common small block sizes that worked in pretty much O(1) time (they just popped an item off the head of a list). This was used as a GP replacement for normal malloc/free libs. When you free a block, it just gets put on the head of the list.

      Tim

  • See HeapAlloc and friends in Win32 for proper implementation.

    At any rate, there are better ways to make sure one never leaks memory problems:

    1) always set a freed pointer to 0. Most architectures have a predictable behavior in dereferencing a 0 (throws an exceptions).

    2) Limit all malloc/free pairs to the same function. If a function just has to allocate and return some buffer, give it a meaningful name to that effect and all a corresponding free version. Then, you can follow the above rule.

    3) assert()s are your friend. Use them religiously. They can always be shut off.

    4) Use memory tracking software (purify) before ship.

    Yes, it's easier to shoot yourself in the foot with C, but you'll gain a huge performance increase. It's all about using the right tool for the right job.
  • by Anonymous Coward on Sunday December 08, 2002 @03:07PM (#4838602)
    why not just use visual basic?

    say what you want about it, you don't have to use stupid hacks to avoid buffer overflows.
  • by ademko ( 32584 ) on Sunday December 08, 2002 @03:13PM (#4838627)
    First off, C++ objects can force the use of all data access through assert()-filled methods, then in optimized mode can be inlined and thus reduced to their C equivalents.

    Second, destructors in C++ guarantee clean up of objects, regardless of how you leave scope (natural, return, exception, etc).

    Finally, you couple destructors and reference counting auto-pointers, and you have yourself a very nice allocation API that's as easy as Java, but without the performance or unnatural destruction logistics.
  • Bite me!
  • by chtephan ( 460303 ) <christopheNO@SPAMsaout.de> on Sunday December 08, 2002 @03:19PM (#4838651) Homepage
    In my last project, I used glib from the ground up. I wrote several thousand lines of code before testing it. I made some very aggressive use of glib and gobject. After the code compiled and did not give any runtime warnings anymore it did not contain a single memory leak (verified using valgrind).

    glib containts a lot of useful things: lists, trees, hash tables, memory pools, string handling functions and a lot more, everything thread safe.

    gobject contains tools on top of glib like "classes" and "objects". It's not the same as in C++ or java, but also very useful. Runtime classes oder data types, generic object properties, reference counting, signal callback, runtime type checking, etc...

    The code ist now full of g_... and it took longer than usual because I had to read the documentation, but I think these libraries are very great, and provide a solution for nearly everything that has to do with abstract data types and dynamic memory allocation.

    And it's very lightweight, fast and efficient.
  • Obstacks (Score:3, Informative)

    by p3d0 ( 42270 ) on Sunday December 08, 2002 @03:42PM (#4838831)
    The "data stacks" described in the article sound like a slightly less-evolved version of GNU obstacks. [gnu.org] The main difference seems to be that the article uses a single global data stack.

    I think the HOWTO should have a reference to obstacks, rather than claiming data stacks are a new invention. (Hint: data stacks have been used many, many times in many, many projects. GNU obstacks are the only one for which I can find a URL at the moment.)

  • String handling:
    std::string MyString("Hello");
    std::string MyCopy(MyString);
    MyString +=(" World");

    and so on.

    And for memory management, head over to BOOST [boost.org] and grab the smart pointers library..

    shared_ptr pMyStruct(new MyStruct());

    which will get garbage-collected when it's no longer needed. Really, c++ does take a lot of the pain out of C programming, without much in the way of downsides. One of the biggest advantages is that you can pick and choose exactly which constructs you want, and the existance of the others doesn't adversly affect you.
  • by lamontg ( 121211 ) on Sunday December 08, 2002 @03:56PM (#4838940)
    From the FreeBSD manpage:

    ALLOCA(3) FreeBSD Library Functions Manual ALLOCA(3)

    NAME
    alloca - memory allocator

    LIBRARY
    Standard C Library (libc, -lc)

    SYNOPSIS
    #include <stdlib.h>

    void *
    alloca(size_t size);

    DESCRIPTION
    The alloca() function allocates size bytes of space in the stack frame of
    the caller. This temporary space is automatically freed on return.

    RETURN VALUES
    The alloca() function returns a pointer to the beginning of the allocated
    space. If the allocation failed, a NULL pointer is returned.

    SEE ALSO
    brk(2), calloc(3), getpagesize(3), malloc(3), realloc(3)

    BUGS
    The alloca() function is machine dependent; its use is discouraged.

    FreeBSD 5.0 June 4, 1993 FreeBSD 5.0
  • What's the gain? (Score:2, Informative)

    You should more clearly mark, what gain can be expected by which measure. Allocating on the stack (with alloca() or something similiar) gains you speed, some convenience, but no security (buffer overflows are more readily exploited to inject harmful code, if the buffer is allocated on the stack).

    You failed to describe what's wrong with strncat(), strncpy() etc. IMHO people who can't comprehend the man pages for those functions probably should avoid C altogether, but definitively must be hindered to write security relevant software (as should sleep-deprived coders who try to do it on a Sunday morning ;-} .

    Said that, I can only appreciate your attempt to raise this issue (once more, maybe for a new generation of C coder).

  • Seems a bit on the "strings" side, so I assume the text is not complete.

    What I wanted to read on was how to create modular programs with C, as in function pointer arrays and how to generally modularize the application. My attempts at building larger apps have resulted in instability, and I do not want to get into C++. Maybe some details on howto allocate mem less frequently in larger chunks would be also useful.. ..just my rusty 2c.
  • scanf and friends (Score:5, Informative)

    by usrerco ( 576913 ) on Sunday December 08, 2002 @04:26PM (#4839164)
    No such document should be without mention of scanf(3) misuse, and gets(3) use at all.

    Regarding scanf(3), many people don't realize this is Bad:

    • char cmd[80], arg[80];
      scanf("%s %s", cmd, arg); // BAD

    This is Good:

    • char cmd[80], arg[80];
      scanf("%79s %79s", cmd, arg); // GOOD

    This prevents a buffer overrun if a word contains 80 or more consecutive non-white characters.

    Ditto for sscanf(3) and fscanf(3). Never forget the N+1 when declaring the arrays (eg. char s[80] vs %79s) to leave room for the NULL.

    Here's a good command to run on all your .c files to find such problems:

    • egrep 'scanf(.*%s' *.c

    ..any lines that match are a potential problem.

    And in a document like this, *definitely* point out the whole gets(3) problem; the granddaddy of them all. Never use gets(3), period. Use fgets(3) instead.

    The gets(3) interface is inherently insecure; a problem waiting to happen by its mere existence. Any code that uses it is broken.

    There are probably some others (someone mentioned strcpy) I'll try to post more if I think of them.

  • I had a quick peruse at the web site. I must admit the vector class in the C++ STL is well worth learning. It's not as quick as the usual error checking you get with arrays, but it is very secure. And once you know that you can move onto lists and maps.

    But hey, it's not C. Ohhhh for a program that is so power hungry I have to write it in pure C. ;o)
  • a Secure, Efficient, and Easy to use Windows OS.
  • by Nevyn ( 5505 ) on Sunday December 08, 2002 @05:12PM (#4839538) Homepage Journal

    Some of the idea's aren't bad (and those have been done before), but mostly it's just another simple dynamic string library in C.

    As for efficency...

    t_strconcat() is one function that I also copied from GLIB. It's a bit dangerous though, the terminating NULL is too easy to forget. I've been thinking about removing it entirely, but it's much more efficient than t_strdup_printf() so I haven't yet had the heart :)

    ...this pretty much speaks for itself. Why Is strconcat() so efficient compared to just doing strcat() multiple times? Because you've got a model for representing the data that has ZERO metadata, and a model for storing the data that requires you to reallocate bits of memory all the time.

    Assuming you can just disacount all this overhead by using memory pools, is a simplistic outlook (for instance even if you waste gobs of memory so you don't have to call malloc that much you'll still need to do copies all the time)

    There are more than a few much better string libraries out there for C. Probably the best for an IMAP server is probably Vstr [and.org] as that was deigned to work well in an I/O context (For instance it doesn't need strconcat() like calls in the API because doing repeat adds is just as fast).

  • about 15 years ago IIRC, see http://herd.plethora.net/~seebs/c/10com.html Still very good advice.

    Never forget that C is just a machine independent assembler, you need to have a good understanding of how machines really work to be able to write good C programs.

    Also: plan the code and code the plan. C is a language that bites you if you are sploppy.
  • by Old Wolf ( 56093 ) on Sunday December 08, 2002 @05:35PM (#4839708)
    Why is this bollocks?

    To summarise the articles: a bunch of small libraries providing object-based memory allocation and string handling.

    Kudos to the poster for enabling himself to write code in a way that's good for him. But that doesn't mean it's good for anyone else.

    For example, I'm not going to go and learn 20 more function names and have more library dependencies and I wouldn't recommend anyone else does either.

    Finally, suppose one wants a better string library or memory library. There are already plenty of good, with-much-work-done-on-them, open source libraries out there. Tried and tested. Not to mention the C++ STL.

    Pick one that means many other people will also be able to read your code and be familiar with the libraries you use! There's nothing I'd hate more than working on a project written by someone using these libraries. Not only do I have to analyze the code, I have to analyze these libraries, and also manage to keep them and their quirks in my head while I am reading the program. Yuck.

  • by wray ( 59341 ) on Sunday December 08, 2002 @06:31PM (#4840077)
    Of course Bjarne Stroustrup [att.com] would say this, but he has some nice examples backing his statements up, too. See his FAQ [att.com] and his paper on "Learning Standard c++ as a New Language" [att.com].

    Stroustrup explains some nice details on especially this issue of memory constructs. He makes a convincing argument for why C++ is easier for C-style programming... Especially for those of you (One I saw below) who "Don't want to get into c++", realize that you can edge into it pretty easily, and accomplish your tasks more easily and quickly -- give it a try!
  • by Moses Lawn ( 201138 ) on Sunday December 08, 2002 @08:55PM (#4840890)
    OK, so that subject's a little inflammatory. But my god, I don't see why anybody is still writing new code in C in this day and age. C++ has been a fast, stable, standardized language for what - 10 years now? All the problems with buffer overflows that require hokey, kludgey workarounds in C are cleanly solved with any well-written string library (like, say, the one in the STL). Memory pools can be nicely wrapped with a class that pushes in the ctor and pops in the dtor, so you don't have to remember to call them in the right order everywhere (just declare an object at the top on the block).

    The arguments I've seen against C++ seem to fall into the following categories:

    * It adds bloat and it's slow
    No, not since optimizing compilers were perfected in the 90s. You can add a lot of overhead to your app by abusing the STL, but for non-trivial applications, you'll never notice it. GCC (at least for the pre-3.0 series) has a really unoptimized template implementation, where "Hello, world" using cout would make a multi-megabyte executable (and be forever compiling it), but more modern compilers, like VC++ and Intel's compiler, do a lot better. Either way, for a real-world app, any size increase will be unnoticable. As for speed, with an optimizing compiler and judicious use of inlining, a C++ program will run just as fast as one written in C.

    These complaints may have been true in the days of the Cfront preprocessor, but not today. I don't know about you, but I no longer write code for a 386 with 4 meg of memory.

    * I don't like/need/want to learn OOP
    You don't need OOP to use C++, but it helps. A class is just a struct where everything's private by default. If you know C, it takes about a day to learn the basics of constructors and destructors, references, and exceptions. Templates and STL will take a bit longer. One great about C++ is that you can just use small bits here and there if you don't want a full-blown OO program.

    * It's not as good as Perl/Python/Ocaml/Eiffel/Java/whatever
    That's not the point. It's not supposed to be. It's supposed to be as good or better than C. If you want a standalone-executable without linking in a complete interpreter and you don't need a lot of string parsing or regexps, you were using C anyway.

    * It won't let me write libraries that work with other languages
    Just declare all of your external APIs using 'extern C' and make sure they only use C types in their signatures. Done.

    The main reason not to use C++ in new development seems to be "I don't want to learn it" or "I don't know anything about it". If you use either one, I don't ever want to work with you.

Math is like love -- a simple idea but it can get complicated. -- R. Drabek

Working...