Berkeley CSUA MOTD:Entry 32805
Berkeley CSUA MOTD
 
WIKI | FAQ | Tech FAQ
http://csua.com/feed/
2025/05/24 [General] UID:1000 Activity:popular
5/24    

2004/8/10-11 [Computer/SW/Languages/C_Cplusplus, Computer/SW/Compilers] UID:32805 Activity:high
8/10    C question.  Is there anything wrong with the following?

        const my_struct_t **pp;
        pp = malloc(sizeof(my_struct_t *));
        pp = realloc(pp, sizeof (my_struct_t *) * 2);

        "gcc -Wall" doesn't complain.  But the M$ compiler (cl.exe) complains
        about the realloc line:

        t3.c(12) : warning C4090: 'function' : different 'const' qualifiers
        t3.c(12) : warning C4022: 'realloc' : pointer mismatch for actual
        parameter 1

        Thanks in advance.
        \_ Your code is correct.  The warnings above are both wrong, and in
           fact the same compiler recognizes the code as safe in C++ mode
           (which is stricter about const).  --mconst
        \_ I'd ask why GCC isn't complaining.  Consts shouldn't change.
           It might be that because there's nothing between the malloc and
           the realloc, GCC is noticing that the value of pp does not actually
           changem while MS sees you are writing to a const and bitches.
           \_ But what I'm trying to realloc is an array of variable pointers
              to constant structures.  The array elements (pointers to constant
              structures, const my_struct_t *) are not consts and do change.
              It's just that the structrues that the array elements point to
              (const my_struct_t) don't change.  I think it's just stupidity on
              M$'s part, but I just want to make sure.
              \_ YMWTS http://www.parashift.com/c++-faq-lite/const-correctness.html
        \_ You sure you're not compiling in MS as a cpp file?
           \_ It works as a CPP file -- see above.  --mconst
           \_ My file is a .c, and I compile like "cl t.c" with no options.
              I tried both version 12 and version 13 and they gave the same
              warning.
        \_ Where is the 'function' name declared?
        \_ BTW, pp = realloc(pp, ...) is a bad idea.  If realloc fails, you've
           just clobbered your old copy of pp and no longer can free it.
           --jameslin
           \_ Yeah I know.  The above was just to illustrate the type checking
              warning.  But thanks.
        \_ Does it still complain if you do something like:
           typedef const struct foo *pfoo;
           ...
           pfoo *p;
           ...
2025/05/24 [General] UID:1000 Activity:popular
5/24    

You may also be interested in these entries...
2014/1/14-2/5 [Computer/SW/Languages/C_Cplusplus] UID:54763 Activity:nil
1/14    Why is NULL defined to be "0" in C++ instead of "((void *) 0)" like in
        C?  I have some overloaded functtions where one takes an integer
        parameter and the other a pointer parameter.  When I call it with
        "NULL", the compiler matches it with the integer version instead of
        the pointer version which is a problem.  Other funny effect is that
        sizeof(NULL) is different from sizeof(myPtr).  Thanks.
	...
2011/3/7-4/20 [Computer/SW/Languages/C_Cplusplus] UID:54056 Activity:nil
3/7     I have a C question.  I have the following source code in two identical
        files t.c and t.cpp:
                #include <stdlib.h>
                int main(int argc, char *argv[]) {
                  const char * const * p1;
                  const char * * p2;
	...
2009/7/21-24 [Computer/SW/Languages/Java] UID:53168 Activity:moderate
7/20    For those who care btw, it looks like eclipse is now A Standard Tool
        at UCB ugrad cs, probably replaced emacs.  Furthermore, people get
        angry at seeing Makefiles, (since eclispe takes care of that).  I
        guess it's just a sign of the times.
        \_ The more people at my work use eclipse the less the code is
           managable in emacs.  I'm not sure which application's fault
	...
2005/2/15-16 [Computer/SW/Languages/C_Cplusplus, Computer/SW/Compilers] UID:36174 Activity:moderate
2/15    Technical question:  we have a memory leak in our C code, we think,
        but it's not the sort of memory leak where the memory's unreferenced.
        What we'd like to do is sort of a poor-man's profile, we want
        to know who calls our memory allocator "New"...  Sorta like a stack
        trace.  Using an actual profiler is sort of difficult 'cause it's
        a parallel application.  Thanks,  --peterm
	...
2004/12/14-15 [Computer/SW/Compilers] UID:35291 Activity:moderate
12/14   If I have a C function like this
        void foo(void) {
          static const char unused1[] = "one";
          const char * const unused2 = "two";
          ...... some code ......
          return;
	...
2004/9/23 [Computer/SW/Languages/C_Cplusplus] UID:33716 Activity:high
9/23    Is the a C++ equivelent to the C realloc function?
        \_ realloc(). But seriously, maybe you want an STL container
           that automatically grows.
           \_ Not in this case.  I just need to grow a char array
              automatically myself.   (For speed reasons) Really, It's a
              very isolated place in the code, and I'll probably just end
	...
2004/5/28-29 [Computer/SW/Compilers] UID:30481 Activity:nil
5/28    I just found out that bison inserts these lines of code
                #ifndef __cplusplus
                #ifndef __STDC__
                #define const
                #endif
                #endif
	...
2004/4/13-14 [Computer/SW/Languages/C_Cplusplus] UID:13175 Activity:high
4/13    How much C++/C knowledge do recent Berkeley CS/EECS grad have?
        \_ Class CSGrad inherits FromDaddy and does not implement C++Knowledge
           very well.
           \_ funny.  just the rich and poor as always.  the middle class can't
              afford education.
        \_ They know how to deal with pointers and addresses, malloc and free.
	...
2003/12/8-9 [Computer/SW/Languages/C_Cplusplus] UID:11356 Activity:nil
12/8    c++ question, how do I overload << in my class so it will handle
        endl? ie: myclass << "some string" << endl
        I know how to do the "some string" part:
                myclass & operator << (const char * s);
        what about endl?
        Thanks!!
	...
2003/12/4-5 [Computer/SW/Languages/C_Cplusplus] UID:11317 Activity:nil
12/4    Is there any reason to worry about mixing the usage of malloc and new?
        Obviously, you can't delete() malloc'd memory (and vv), but aside from
        that, will bad things happen?  Oh, I should note that this is for a C
        library that is used by C++ -- a coworker suggested wrapping my memory
        allocations (and deletions) with
        #ifdef __cplusplus
	...
2003/9/10 [Computer/SW/Languages/C_Cplusplus] UID:29529 Activity:nil
9/10    Stupid question: how do I reference a C callback?
        int mycompare(void const *a, void const *b) { ... }
        qsort(msg, sizeof(Msg), numMsgs, mycompare);
        I get
        "Type error in argument 4 to `qsort'; calling convention mismatch."
        \_ There's nothing wrong in the you reference it.  However, you should
	...
2010/1/22-30 [Computer/HW/Laptop, Computer/SW/OS/OsX] UID:53655 Activity:high
1/22    looking to buy a new development laptop
        needs ssdrive, >6 hr possible batt life, and runs linux reasonably
        Anyone have a recommendation? Thx.
        \_ thinkpad t23 w ssdrive and battery inplace of drive bay
        \_ Ever wondered what RICHARD STALLMAN uses for a laptop?  Well,
           wonder no more!
	...
2009/8/31-9/9 [Computer/SW/Compilers] UID:53312 Activity:nil
8/31    I'm trying to learn ActionScript, like a step by step tutorial.
        The site at http://www.actionscript.org/resources/categories/Tutorials/Flash/Beginner
        isn't well organized. It doesn't explain how to get started with
        an editor, compiler, IDE. And should I even learn AS2 when you can
        learn AS3? Is Adobe Flash CS4 >>> CS3 or just CS4 > CS3?
	...
2009/2/28-3/11 [Computer/SW/Compilers] UID:52661 Activity:nil
2/28    I'm looking for a recommendation of a compiler/IDE to use to
        develop C/C++ code under Linux. In school, we used jove/gcc and
        I still use emacs/vi and gcc to this day. However, it is really
        lacking. Under Windows I tried Visual Studio and there were some
        really nice things about it, although it was so overwhelming that
        after 6 months of occasional use I still didn't really know what I
	...
2008/6/9-12 [Computer/SW/Languages/C_Cplusplus, Computer/SW/Security] UID:50194 Activity:nil
6/8     CSUA code guru please help. I need to see my random number
        generator with a good seed (I just need random 18 bit
        identifiers). The usual time(NULL) is OK, except my program
        might be invoked faster than once a second, and seeding using
        time() produced the same result. I tried clock() but it seems
        to return 0. My program needs to be run in Linux/DOS (Watcom
	...
2008/5/2-8 [Computer/SW/Compilers] UID:49874 Activity:low
5/2     How do I get the L1/L2 cache size and cache line size on my machine?
        Can I find this stuff out at compile time somehow?
        \_ You aren't planning on running your code on any other processors?
        \_ May I ask what it is you want to achieve ultimately? If you don't
           know your architecture and want to find out dynamically, there are
           tools that can peek/poke to give you definitive answers, plus you get
	...
2008/4/2-6 [Computer/SW/Languages/C_Cplusplus] UID:49645 Activity:moderate
4/2     Is there an interpreted version of C or C++ that can be used for
        educational purposes? It doesn't have to be full-featured or
        strictly adhere to the standards, but it's painful for students
        to change a variable in a for loop and then wait for a compile
        to see how it changes the result. Something really lightweight
        would encourage them to play around a lot more and learn more in
	...
2007/11/30-12/6 [Computer/SW/Compilers, Computer/HW/CPU] UID:48719 Activity:moderate
11/29   From the CSUA minutes:
        - Next Gen Console
        -- If we have $1800 in our accounts, should we buy a console:
           4 votes passes.
        -- Console voting: 2 votes each, neither passes
           * 360 = 600, more games
	...
2007/11/27-30 [Computer/SW/Languages/C_Cplusplus, Computer/SW/OS/Solaris] UID:48701 Activity:high
11/27   I'm using select to do a nonblocking check to see if a single socket
        has anything to read off it.  Problem is, I can have up to 12228
        file descriptors, and Linux fd_set only supports up to 4096.  Any idea
        what I can do about this?  (Or a better solution?) -jrleek
        \- 1. who are you
           2. i am busy this week and you didnt mention language
	...
2006/11/10-12 [Computer/SW/Compilers] UID:45316 Activity:nil
11/10   Is there anyway to get C/C++ compilers to automatically compile
        different code for different processors?  I'd like to be able to
        say something like:
          #if defined X86 ...
          #elif defined SPARC ...
          #else ...
	...
Cache (8192 bytes)
www.parashift.com/c++-faq-lite/const-correctness.html
It means using the keyword const to prevent const objects from getting mutated. For example, if you wanted to create a function f() that accepted a std::string, plus you want to promise callers not to change the caller's std::string that gets passed to f(), you can have f() receive its std::string parameter... This check is done entirely at compile-time: there is no run-time space or speed cost for the const. In the pass by value case (f3, the called function gets a copy of the caller's std::string. This means that f3() can change its local copy, but the copy is destroyed when f3() returns. In particular f3() cannot change the caller's std::string object. As an opposite example, if you wanted to create a function g() that accepted a std::string, but you want to let callers know that g() might change the caller's std::string object. In this case you can have g() receive its std::string parameter... Thus they can pass their std::string to any of the f() functions, but only f3() (the one that receives its parameter "by value") can pass its std::string to g1() or g2(). If f1() or f2() need to call either g() function, a local copy of the std::string object must be passed to the g() function; the parameter to f1() or f2() cannot be directly passed to either g() function. In particular, no changes will be made to the const parameter that was passed by reference to f1(). How is "const correctness" related to ordinary type safety? Declaring the const-ness of a parameter is just another form of type safety. If you find ordinary type safety helps you get systems correct (it does; especially in large systems), you'll find const correctness helps also. Should I try to get things const correct "sooner" or "later"? Back-patching const correctness results in a snowball effect: every const you add "over here" requires four more to be added "over there." non-const member function called mutate(), saying p->mutate() is an error (the error is caught by the compiler; no run-time tests are done, which means const doesn't slow your program down). non-const member function called mutate(), saying xmutate() is an error (the error is caught by the compiler; no run-time tests are done, which means const doesn't slow your program down). In other words, "Fred& const x" is functionally equivalent to "Fred& x". Since you're gaining nothing by adding the const after the &, you shouldn't add it since it will confuse people. const Fred& x However, the real question is which should be used. Answer: absolutely no one should pretend they can make decisions for your organization until they know something about your organization. there is no "right" answer for all organizations, so do not allow anyone to make a knee-jerk decision in either direction. For example, some organizations value consistency and have tons of code using const Fred&; for those, Fred const& would be a bad decision independent of its merits. There are lots of other business scenarios, some of which produce a preference for Fred const&, others a preference for const Fred&. Use a style that is appropriate for your organization's average maintenance programmer. Not the gurus, not the morons, but the average maintenance programmer. Unless you're willing to fire them and hire new ones, make sure that they understand your code. Make a business decision based on your realities, not based on someone else's assumptions. You'll need to overcome a little inertia to go with Fred const&. Most current C++ books use const Fred&, most programmers learned C++ with that syntax, and most programmers still use that syntax. That doesn't mean const Fred& is necessarily better for your organization, but it does mean you may get some confusion and mistakes during the transition and/or when you integrate new people. Some organizations are convinced the benefits of Fred const& outweigh the costs; const Fred* x However, the real question is which should be used. Answer: absolutely no one should pretend they can make decisions for your organization until they know something about your organization. there is no "right" answer for all organizations, so do not allow anyone to make a knee-jerk decision in either direction. For example, some organizations value consistency and have tons of code using const Fred*; for those, Fred const* would be a bad decision independent of its merits. There are lots of other business scenarios, some of which produce a preference for Fred const*, others a preference for const Fred*. Use a style that is appropriate for your organization's average maintenance programmer. Not the gurus, not the morons, but the average maintenance programmer. Unless you're willing to fire them and hire new ones, make sure that they understand your code. Make a business decision based on your realities, not based on someone else's assumptions. You'll need to overcome a little inertia to go with Fred const*. Most current C++ books use const Fred*, most programmers learned C++ with that syntax, and most programmers still use that syntax. That doesn't mean const Fred* is necessarily better for your organization, but it does mean you may get some confusion and mistakes during the transition and/or when you integrate new people. Some organizations are convinced the benefits of Fred const* outweigh the costs; A member function that inspects (rather than mutates) its object. A const member function is indicated by a const suffix just after the member function's parameter list. Member functions with a const suffix are called "const member functions" or "inspectors." Member functions without a const suffix are called "non-const member functions" or "mutators." The trailing const on inspect() member function means that the abstract (client-visible) state of the object isn't going to change. This is slightly different from promising that the "raw bits" of the object's struct aren't going to change. Another (important) insight from this aliasing issue: pointing at an object with a pointer-to-const doesn't guarantee that the object won't change; it promises only that the object won't change via that pointer. What do I do if I want a const member function to make an "invisible" change to a data member? By saying the changes are "innocuous," I mean that the changes wouldn't be visible from outside the object's interface (otherwise the member function would be a mutator rather than an inspector). When this happens, the data member which will be modified should be marked as mutable (put the mutable keyword just before the data member's declaration; This tells the compiler that the data member is allowed to change during a const member function. If your compiler doesn't support the mutable keyword, you can cast away the const'ness of this via the const_cast keyword (but see the NOTE below before doing this). Therefore you can use self to modify the object pointed to by this. NOTE: there is an extremely unlikely error that can occur with const_cast. It only happens when three very rare things are combined at the same time: a data member that ought to be mutable (such as is discussed above), a compiler that doesn't support the mutable keyword, and an object that was originally defined to be const (as opposed to a normal, non-const object that is pointed to by a pointer-to-const). Although this combination is so rare that it may never happen to you, if it ever did happen the code may not work (the Standard says the behavior is undefined). If you ever want to use const_cast, use mutable instead. In other words, if you ever need to change a member of an object, and that object is pointed to by a pointer-to-const, the safest and simplest thing to do is add mutable to the member's declaration. Please don't write and tell me that version X of compiler Y on machine Z allows you to change a non-mutable member of a const object. I don't care -- it is illegal according to the language and your code will probably fail on a different compiler or even a different version (an upgrade) of the same compiler. This can happen only in rare cases (when the object is constructed in the scope of the const member function invocation, and when all the non-const me...