Slashdot Mirror


User: try_anything

try_anything's activity in the archive.

Stories
0
Comments
973
First seen
Last seen
Profile
(view on slashdot.org)

Comments · 973

  1. Re:Bad examples on Pros and Cons of Garbage Collection? · · Score: 1

    I can think of some reasons why this would be hard, but none why it would be impossible. It does make it impossible to verify that a resource is properly disposed without verifying that none of the functions further out on the call tree accidentally maintain a reference. A nice feature of guaranteed destruction is that it allows me to glance at the function where the resource is allocated and quickly see that it can't be leaked.

    I would prefer that the type system enforce limitations to guarantee both safety and predictable destruction. How about this:

    * Every object has a scope, specified at its construction.
    * Some objects are garbage-collectible; others are guaranteed to be coextant with their scope. This is specified when the object is constructed.
    * Objects may only contain references to objects that belong to the same scope or a strictly larger scope.

    When an object is automatically destroyed as its scope exits, all valid objects that reference it are either eligible for garbage collection or schedule for immediate destruction, so there is no problem of integrity, except the inevitable problem that arises when destroying objects that reference each other.

  2. Re:C++ basically has it right on Pros and Cons of Garbage Collection? · · Score: 1

    Sure enough when people are learning how to write programs, it's far better to use a language garbage collection, so that one has to really understand what's happening.

    This is something that I have yet to figure out. On one hand, I think it's important for programmers to understand the machine that their code runs on. On the other hand, I wonder if it's possible for a programmer to achieve a useful level of understanding of what's "really happening." To be useful, a model must be simple enough to enable reasoning, be accurate enough to provide useful answers, and specify its limitations. How many people have such a model of, say, a Xeon processor or their language's implementation of memory management?

    I think it's more important for beginning programmers to learn to program the abstract machine that their language presents to them, rather than the "real" or "bare metal" machine they are taught to believe in. These abstract machines are specified in language definitions and guaranteed by language implementers, so they are real enough to be depended on and reasoned with. Garbage collection or not, that makes them much more real than a programmer's imagination of how a program gets implemented by the platform.

  3. Re:GC is DRY on Pros and Cons of Garbage Collection? · · Score: 1

    This isn't necessarily true. Take a look at some of the C++ examples posted in the thread. The C++ model is based around *never* (well, almost never) writing a line of code to release any resource. If you type

    scoped_ptr foo(new string);

    you never have to worry about deallocating or leaking the string. This makes RAII quite compatible with DRY. C++ memory management still leaves much more scope for errors than garbage collection, though.

  4. Re:Bad examples on Pros and Cons of Garbage Collection? · · Score: 1

    If you accept automatically-destroyed stack objects in a GC language, you have to face the possibility of heap objects containing dangling pointers to destroyed stack objects. So there's a tradeoff even in that situation: you allow a certain class of memory errors, or you create a language feature that prevents garbage-collected objects from referring to stack objects.

  5. Re:Don't know what to say here... on Pros and Cons of Garbage Collection? · · Score: 1

    RAII originated (as far as I know; someone may be able to correct me) as an idiom for using C++ language mechanisms to manage resources. Without knowing those mechanisms, it's hard to see how RAII helps. Here's an example, though:

    int foo()
    {
    ScopedLock lock(getBarMutex());
    if(twiddleBar()) return 1;
    if(diddleBar()) return 2;
    if(fiddleBar()) return 3;
    return 4;
    }

    Here, the method could exit at four different return points, not to mention the possibility of an exception being thrown. Without RAII, you would need a complex control structure to guarantee that the mutex lock was released. Using RAII, you simply put the mutex acquisition in ScopedLock's constructor and the mutex release in ScopedLock's destructor. Because the language guarantees that the lock's destructor will run when you leave the scope, you don't have to worry that some set of conditions will cause the thread to leave this function without releasing the mutex. Without that guarantee, the function would need to be more complex. It would have more lines and a more complex control structure. And no amount of code gives you the confidence that language enforcement does.

    I hope that intrigues you enough to check it out! Be warned, though, RAII requires certain language features, so you may not be able to use it in your language of choice.

  6. Re:If C++ Memory Management on Pros and Cons of Garbage Collection? · · Score: 2, Interesting

    I agree with a comment posted elsewhere that unchecked memory access and manual memory management, while both unsafe and fertile sources of errors, are different beasts.

    Manual memory management is a control issue. Unchecked memory access is a matter of asceticism.

    Buffer overruns happen because the devotion to performance and minimalism among a certain crowd is religious. Because of this, the C++ standards guys were terrified of encouraging the use of anything slower and safer than what a C programmer would do. In std::vector and boost::array the default (and readable) access operator [] is unchecked, and checked access is relegated to the ugly at() method. This is a political decision that turns on its head the principle that quiet syntax should be used for routine, safe operations and ugly syntax should be used for rare, dangerous operations.

    Using template metaprogramming, it's easy to produce your own array classes with bounds-checking chosen at compile time, but because the survival of C++ depended on the "just as fast as C!" slogan, unchecked access was officially encouraged and has unsurprisingly become the norm among C++ developers.

    Rationally, even a developer who expects that bounds checking will always be too expensive in production should insist that bounds checking be easily enabled at compile time. Electric Fence helps with that, but template metaprogramming is a more straightforward solution.

  7. Re:Pros and cons on Pros and Cons of Garbage Collection? · · Score: 0, Flamebait

    Or maybe I'm the only one.

    You're certainly not. I would be pretty pissed off if someone kept telling I had a memory leak in my Java program when he really meant that I was wasting memory by keeping objects "live" longer than necessary. And I suspect the ones who got their noses rubbed in it think he's a jerk for using terminology in an unexpected way and then treating them like they're stupid for not understanding it.

  8. Re:C++ basically has it right on Pros and Cons of Garbage Collection? · · Score: 3, Insightful

    I don't think garbage collection implies treating the programmer like an idiot. The programmer's attention is a finite resource that is often better spent on something other than memory management, especially given that garbage collection performs quite adequately for many programs. A Perl, Java, or Lisp programmer isn't an idiot for not doing his own memory management any more a person who doesn't make his own shoes is an idiot.

  9. C++ and others.... on Pros and Cons of Garbage Collection? · · Score: 5, Interesting

    C++'s constructor/destructor paradigm with predictable object destruction has the benefit of enabling the RAII (Resource Acquisition Is Initialization) idiom. RAII and exceptions greatly simplify resource management in the presence of error handling. Still, even as someone who knows C++ better than I know any other language, I have to admit that for many applications a garbage collected language puts the least mental burden on programmers and produces the fewest memory errors. The burden of arranging all the extra try/catch blocks in Java (because it lacks RAII) has to be weighed against the burden of investigating and fixing memory management errors in C++, and for people using new/delete, Java wins, IMHO.

    C++ programmers should be making very little use of new and delete, though; they should be using smart pointers. I think the article poster misunderstands smart pointers. boost::shared_ptr is a reference counted pointer, but std::auto_ptr and boost::scoped_ptr have nothing to do with garbage collection - they certainly aren't "faked garbage collection" and they certainly aren't unpredictable. They use C++'s object scoping and copying mechanisms to manage memory in a way completely unlike garbage collection. scoped_ptr is the simplest and most predictable memory management tool of all. Taking programmer error into account, it's more predictable than using delete. Even shared_ptr is predictable; when the reference count falls to zero, the object is immediately destroyed, not just marked for destruction.

    Sadly, although C++ is a very powerful language and can be used to write code with few errors, the language as used by beginners is as dangerous as C, perhaps even more dangerous. It takes programmers years to become proficient in all the methods and idioms that make C++ a usable language.

    (I would love to see a language that allows programmers to choose scoped allocation, smart pointer heap allocation, or garbage-collected heap allocation, and uses types to avoid dangerous combinations such as garbage-collected objects pointing to scoped objects or an object pointing to an object in an unrelated scope. Every object would have two types - the object type (int, file, circle, etc.) and the memory management type (scoped with scope S1, scoped with scope S2, garbage-collected, etc.))

  10. Re:Ideas on Building Distributable Linux Binaries? · · Score: 1

    Just curious, why avoid Boost? Most of Boost is template code, so it gets compiled into your objects and doesn't leave any library dependencies. I use Boost heavily and distribute to customers who don't have it installed.

  11. Re:Don't try to play Operating System on Reducing Firefox's Memory Use · · Score: 1

    Was this admonition aimed at FireFox developers or Microsoft Windows developers?

  12. Invent a cure for stupidity on How To Fight Nigerian Scams as an Honest Nigerian? · · Score: 1

    Then, no more scammees, no more scammers, no more suspicion.

    But seriously, no one trusts anyone on the internet. They trust intermediaries like PayPal, Amazon, and credit card companies to accept some risk and some responsibility for policing the transaction. You need to contact those companies individually and ask them what you need to do so they'll allow you to do business through them. I'm sure you can work something out without waiting for the whole scam industry to disappear.

  13. Text editor, email on What Tools Do You Use for UI Prototyping? · · Score: 1
    But maybe you meant to say GUI.

    :-P

  14. What boring choices on Space.com's Top 10 Space Movies of All Time · · Score: 1
    Having said that, I just wrote up a list of movies they left out and then realized that only a few of them were "Space Movies." (Most of my favorite sci-fi movies aren't space movies. Who'd a thunk it?) One space movie that clearly belongs on this list, however, is Solaris.

    --- the rest of my non-space list ---
    Blade Runner, Abre los ojos, Brazil, Delicatessan, Hombre mirando al sudeste (remade into a Robin Williams crapfest), Metropolis, Eternal Sunshine of the Spotless Mind

    Last and probably least, They Live has a kind of genius shittiness to it. It's painful to watch, yet always fondly remembered (leading you to inflict it on yourself several times before you learn your lesson).

  15. Re:Human translators not very reliable either on Computer Translator Ready for Testing in Iraq · · Score: 1

    Yes! I've seen something virtually identical on TV. A translator translated "Much better, we got A right, but now we need to concentrate on B. Let's try again and pay careful attention to floodling the B." to "OK, he's pleased by your progress, now try again."

    Even worse is when translators are rewarded for skewing to what the audience wants to hear. Television translators are the worst. When the mayor of a small town in a Latin American country says:

    "It's very difficult to ship goods to the city because this road was damaged by a flood almost a year ago. We've requested funds from the federal government to repair this road multiple times over many months, and we haven't received a satisfactory response. There is a government project for exactly this kind of thing, but the official who controls the money is from a party that gets no support here, so he sends the money elsewhere."

    How do you make that interesting and satisfying to an American audience?

    Well, liberals love hearing about simple helpless people who need to be saved from injustice. Conservatives love hearing that poor countries are that way because the people are all corrupt, stupid, and/or lacking in initiative. So, just add an English voice-over in a slow, heavily accented dumb peasant voice:

    "Things are very bad here since the flood. We need money to repair this road. When we ask the government for money it ignores us. The government is supposed to help us but it is bad and corrupt."

    Bingo. Now you have television.

  16. Re:You should still know on What Workplace Coding Practices Do You Use? · · Score: 1
    I hate Hungarian because you know the type from the context anyway. You don't do addition on a list. You don't do foo[bar] on a real.

    I'm a little late to the party here, but I hope by "context" you mean the variable's type declaration or (if there is no type declaration) the source of the variable's value. If not, I should warn you that there's crappy code out there written by people who haven't yet learned that in software, "unexpected" almost always implies "crappy." I know this because I wrote some back when I was a math major who didn't know much about software.

    One thing I did was define addition on lists so I could use lists to represent polynomials :-)

    template<class T> vector<T>& operator+=(vector<T>& poly1, const vector<T>& poly2) { /* etc. */ }

    ...in a header file, in the default namespace. My goal was to make my code look as much as possible like math. Another thing I did was figure out how to abuse C++ so I could write floor[x] and ceiling[x] to get the floor and ceiling of x, which looked better to me than floor(x) and ceiling(x) because the square brackets reminded me of the symbols I used when writing math out by hand.

    Now you're going to be tossing and turning all night with nightmares of having me as a coworker, but try not to worry, I swear I've reformed :-)

  17. Be picky about what you cover on What Workplace Coding Practices Do You Use? · · Score: 2, Interesting

    There are three categories of standards:

    1) First, there are arbitrary choices where uniformity across the company is more important than having a perfect fit for each project.

    A perfect example is the choice of information management tools and formats. Unlike an indentation style, a source control or bug database learning curve can be a significant barrier to a developer helping out another team for a few days. It's also important to ease access for non-development personnel. Pick some tools and make everyone use them.

    "Every project shall use Subversion as its source control system, BugZilla as its bug tracking system, and DocBook for user documentation."

    Depending on the size of your company, the choice of a unit test framework or a build tool might be standardized. Keep in mind the benefit of diversity in these matters, though.

    2) Second, there are matters of practice that can be fairly unambiguously stated and checked.

    A few examples:

    "Every project shall version its acceptance tests."
    "Every project shall archive acceptance tests and test results for every software release."
    "Every project shall publish a current schedule, updated daily, and a summary of outstanding defects, updated at least weekly, to the IT intranet."
    "Every project shall maintain a system of peer review, so that all code must pass by a second pair of eyes within a week of being committed."
    "Every project shall automatically generate API documentation."

    3) Third, there are matters that may be important but shouldn't be included in your standards.

    There are two good reasons for being so picky. First, you want your standards to be as short as possible so people actually read them. Second, you don't want to publish standards that you can't or shouldn't enforce.

    An example of a good coding rule that doesn't fall into the first two categories is "Document intent, not mechanics." Everyone should do it, but checking and enforcement should be done among project teammates, not by a higher level of management.

    Another example is "Test everything that can break." The extent of test coverage can only be determined by people actually working on the project, so you can't enforce this rule. It's a great rule, but it doesn't belong in your standards.

    Since so much attention has been paid in other posts to matters of code formatting, I might as well add my two cents. For languages where there is One True Way, such as Java and Python, there's no good reason to deviate from the One True Way. Is it really your job to point out and enforce the obvious? I don't think so. Let the project managers handle it.

    For other languages, such as C++, there are a variety of accepted styles. Uniformity is good, and every project should certainly pick a style and use it consistently. Whether to pick a uniform style for the company is a judgment call. Professional C++ programmers are used to dealing with variety and shouldn't have problems switching when they jump from project to project. For your company the right rule for dealing with C++ projects may be this:

    "Every project that uses C++ shall adopt and publish a uniform brace and indentation style."

    Or it may be this:

    "All C++ code shall be formatted as in The C++ Programming Language, Special Edition."

    A final note: Be firm about setting standards, but talk to people first and don't issue any orders that you don't have the muscle to enforce. Find out what people's prejudices are and eagerly defer to them when it doesn't make much difference. Migrating CVS users to Subversion should be no big deal, but if a bunch of stubborn CVS users refuse to migrate, and you fail to make them, all the rest of your standards will go out the window as well. If your authority is shaky, the best way to shore it up is to avoid controversy and issue a bunch of commands that nobody minds obeying ;-)

  18. Re:Why? on Dynamic Memory Allocation in Embedded Apps? · · Score: 1
    One reason I might be tempted to stay away from C++, is once you use it, you might want to use STL or boost.

    Good idea, stay away from languages with big libraries. That way you have to use third party libraries or implement everything yourself, and then you'll know everything is correct and efficient ;-)

    I'm mostly kidding. I was going to blast you until I remembered that code size, unlike execution time, can't be dramatically improved by making isolated tweaks. I'm guessing it is not pleasant to go through your code and replace every use of a std::vector<T> or std::set<T> for some T, in order to save the memory footprint of that class.

  19. Re:Internet freedom isn't going anywhere. on Flushing the Net Down the Tubes · · Score: 2, Insightful

    That cheap, easy, and free quality is purely accidental and is exactly what needs to be protected. The internet happens to be the way it is because of its history. It became indispensable before governments had time to take control. The Saudi government would have created an internet that sent an email to the police when a woman logs on, the US government would have created an internet that couldn't be used without paying a corporation, and every government would have created an internet that gave it complete surveillance power over users within its borders. For now, governments must accept the internet as it is, but they will work to correct these perceived shortcomings, and hence destroy the free nature of the internet.

  20. Re:Cluestick on Dynamic Memory Allocation in Embedded Apps? · · Score: 1

    I can see your objection to auto_ptrs.  They're most often used as class members (for which boost::scoped_ptr is superior, IMO), which doesn't apply when comparing to C.  They're mostly useful for polymorphism, or when a function returns a pointer that the caller is supposed to deallocate.  Here's an example similar to code in my current project:

    void process_file(const string& filename)
    {
        boost::scoped_ptr<DataFile> file(open_data_file(filename));
        // process the file, possibly throwing an exception for a malformed file
    }

    (The main difference between a scoped_ptr and auto_ptr is that a scoped_ptr is noncopyable, so you're less likely to do something with it that you don't expect.)

    Different classes are used to process different types of files, so an ABCFile would be created to read "foo.abc" and a DEFFile would be created to read "foo.def".  The open_file function (provided to me in a library) takes care of that.  In case of a failure, this function doesn't care about the exact reason, it only cares that resources are cleaned up and the reason for the failure (encoded in the exception) is propagated to the caller.

    As you see here, interfaces between libraries usually aren't as safe as they could be.  In this case, the open_file function returns a raw pointer, which could easily be leaked.

  21. Re:Cluestick on Dynamic Memory Allocation in Embedded Apps? · · Score: 1

    You missed the point about omitting delete. C++ programmers only write deallocation code in a very few carefully examined places; everywhere else, they use RAII. C programmers have to manually pair allocation and deallocation, AND they have to take care of the error-handling cases by hand.

  22. Re:Cluestick on Dynamic Memory Allocation in Embedded Apps? · · Score: 1

    First, given the C++ code above, you merely need to reimplement the new operator, and voila, you're using a different allocation scheme, possibly with extra debugging code that you can compile in when you want it.

    Given the C code above, you have to search and replace on malloc and free if you want to tinker with allocation. Very bad.

    Second, a C++ programmer would not write that C++ code. He or she would use std::auto_ptr or boost::scoped_ptr instead of calling delete.

  23. Re:Why? on Dynamic Memory Allocation in Embedded Apps? · · Score: 2, Insightful

    C++ imposes hardly any run-time cost, and in most cases none at all, if you turn off exception handling and RTTI. This has been an explicit design goal of C++ since the beginning. Any problem that forces you into the situation you describe (which I think is inheritance with virtual functions) would require an equally complex C solution which would be harder to read and would probably compile to slower code since C++ compilers use implementation tricks that can't be expressed in C.

    The proof of this is that (almost) any standard C program can be turned into a standard C++ program with trivial changes (modulo some C99 stuff like complex numbers). If you can write C code that is faster or more predictable than C++ code, simply do so. Then rename your .c files to .cpp ;-)

  24. Take exactly what you need on Dynamic Memory Allocation in Embedded Apps? · · Score: 2, Insightful

    Do you know exactly how much memory you need? If so, allocate it statically.

    If you don't, there's no good way to avoid dynamic allocation. The best you can do is allocate a certain amount statically and try to get by with that. If you need more, you have to throw an error. If you need less, you're a memory hog - not a good thing in an embedded program.

    Dynamic memory management isn't so scary in C++. If you absolutely have to use C, God be with you.

  25. Re:Why? on Dynamic Memory Allocation in Embedded Apps? · · Score: 3, Interesting
    I second sticking with C++. The poster may have a good reason for switching to C, but he should have explained it, because the difference between C and C++ is extremely relevant to his question! Thanks to RAII and smart pointers like boost::scoped_ptr (see boost.org) C++ is way ahead of C for using dynamic memory allocation safely and readably. Switching to dynamic allocation will likely involve much greater cost in bugs and readability if C is used instead of C++.

    Also, if performance is important, it's important to be able to experiment with allocation methods when you run into problems. In C++, the ability to implement new and delete differently for each class allows you to experiment with custom allocators without rewriting your code, even if you didn't think of it beforehand. If you use C, make sure you wrap your calls to malloc and free in case you need to tinker later!