Thread: Casting malloc?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    malloc returns a void pointer...what this means is that the return points to something, but that something could be more or less anything......so what you are doing above is giving a hint to the compiler that the data returned from malloc should be treated as a pointer to a char (or an array of chars).......

    in std C, there's no need to cast from malloc, but of you are compiling your code as C++, it will give an error without the cast being present.....this is due to C++ being more type sensitive (it has to be due to its ability to define custom types)

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793

    Re: realloc

    Originally posted by pnxi
    By the way, can any body expain how to use realloc() function, and it is better to use a example.
    Thanx for help!
    Try a search

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    casting is where you (the programmer) decide that you know better than the compiler.

    So when you say this
    (char*)malloc(10)

    You're saying that you take whatever malloc returns, convert it to a char*, and assign that to the variable in question.

    This is all well and good if malloc is prototyped properly (by including stdlib.h), where it's defined as returning void*.

    The problem comes in when you fail to include stdlib.h, and the compiler initially assumes that malloc returns an int. The real problem is, you DONT get any warning from the compiler.

    You merrily then convert that int to a char* (via the cast). On machines where sizeof(char*) is different from sizeof(int), the code is seriously broken.

    Now if you just have
    char *var = malloc( 10 );
    And you miss out the include <stdlib.h>, you will get a warning from the compiler.

    http://www.eskimo.com/~scs/C-faq/s7.html

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    > you would be better to do this:
    In C, yes

    But note Fordy's comments about C++

    But in C++, you should be using the new operator to get more memory, not malloc

  5. #5
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    Well look at this way. When you want to find the sin of int x do
    you do sin(x) or sin((double)x). Both are correct and both
    coerse the type. Use whatever
    you think looks best. Not including stdlib.h is kind of non-issue.
    Anyone using a c compiler without turning on warnings
    for this should not be programming.

  6. #6
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    Maybe, but if your that asleep maybe you would cast
    to the wrong type.

  7. #7
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    First off I would like to point out to everyone that says "don't type cast malloc()" that just because you don't need the type cast doesn't you shouldn't. malloc(), calloc(), and realloc() are part of the standard C memory manager. Check this out:

    Code:
    int *i = malloc(1);
    This will return a pointer to a block of memory that is not big enough to accomodate the size of an int.

    Code:
    int *i = (int *)malloc(1);
    This code still erroneous. So therefore I do not understand why people take issue with the cast (which is meaningless) if the only provision here is compatibility with older compilers. I did take note that syntax can be an issue with some compilers, however, a compiler that gives you grief over simple code such as this is not not a great compiler. If you look through my code you will always see a cast in front of all my mallocs, callocs, and reallocs only out of habbit. This is an issue of personal opinion.

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Then you don't fully understand my point.
    Allow me to take a stab at it. You are saying that the following code is wrong if I wanted to simulate an array of integers:
    Code:
    #include <stdlib.h>
    /*
    ** my_header.h declares a to be a pointer to double
    */
    #include "my_header.h"
    
    int main ( void )
    {
      a = malloc ( 24 * sizeof *a );
    
      return 0;
    }
    
    No warnings.
    As it is the compiler implicitly converts the void pointer to a double pointer, the usage is correct, but not what you wanted. If, however, you had included a type cast to int * the compiler would likely give you a warning about incompatible types:
    Code:
    #include <stdlib.h>
    /*
    ** my_header.h declares a to be a pointer to double
    */
    #include "my_header.h"
    
    int main ( void )
    {
      a = (int *)malloc ( 24 * sizeof *a );
    
      return 0;
    }
    
    C:\C\C.c(9) : warning C4133: '=' : incompatible types - from 'int *' to 'double *'
    This is a valid point, but so is the case for not using type casting. In the end, not using type casting is encouraged, but it is very largely a matter of style.

    -Prelude
    My best code is written with the delete key.

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    To make it simple to understand...

    Think of a void pointer as a union that has reference to every single type of data you could ever possibly think of. Hehe.

    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Regarding the usage of malloc, I prefer:

    TYPE *ptr;

    ptr = malloc( sizeof( TYPE ) * NUMBER_TO_ALLOCATE );

    There is no benefit I can see to ever casting, unless you are implicitly converting from one type to another. In malloc's case, there is no reason to ever cast that I can envision. The return type of malloc is to a continuous block of N bytes where N is:

    sizeof( TYPE ) * NUMBER_TO_ALLOCATE

    As such, it really doesn't matter what it's cast into, the cast is a moot point. Once a pointer is pointing at some block of memory, it could care less what type it was cast to when it was originally set to the address.

    Setting a pointer to point to an address does not change its type. As such, there is nothing that casting pointers from one type to the next provides, other than preventing your compiler from yelling at you. Example:

    char *c;
    int *i;
    float *f;

    f = (float*) i = (int*) c;

    This will (I believe, haven't bothered trying it) prevent your compiler from *****ing at you, but the end result is irrelevent.

    In the end, they all point to the same spot in memory, and in the end, when you increment any of them, they only increment by N bytes, where N is the size of each variable.

    So the end result is, it doesn't matter what you cast a pointer to, it will still be its own type, and nothing you can do will change that, unless you implicitly force cast it in incrementation:

    ((float*)c)++;

    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by JoeSixpack
    The cast (if used) is you telling the compiler that this is what you meant.
    You're missing the point. The compiler doesn't CARE what you cast to. It has no effect. There is no point what so ever in casting malloc! It provides NOTHING to your code. It is worthless. It doesn't MATTER what you cast to, because you are casting a VOID POINTER. Void pointers, as far as your compiler is concerned, can go to ANYTHING, and there is absolutely no point what so ever in casting the return.

    You're just asking your compiler to yell at you by possibly casting it to the wrong type. There is no benifit what so ever in casting a void pointer. Period. Ever. End of story.





    Originally posted by JoeSixpack

    No, it's not meant to. It's so the compiler can give an error/warning. If you assign a block of memory to a different type of pointer than you had intended it may not have the desired affect.
    We're talking about void pointers. There is no reason to ever cast a void pointer. Your compiler will not complain about it, because it is impossible to cast a void pointer to the wrong type. Ever.

    The only reason you could ever possible get this wrong is if you typed the single malloc line wrong:

    char * c = malloc( sizeof(float) * 100 );

    And even then, it still won't care. The only way it would care, would be if you cast it implicitly. Why on earth would you?

    char * c = (float*) malloc( sizeof( float ) * 100 );

    And that's absurd. Why on earth would you ever do that? There is no point in EVER casting void pointers. Period.

    Originally posted by JoeSixpack

    Exactly, but if you want a block of memory that can be manipulated in 1 byte regions, but allocate it to a pointer that increments/decrements in 4 byte regions then the pointer isn't going to care that you've made a mistake. However, casting the return value of malloc allows your compiler to provide a warning to this affect.
    Yes, but how in the hell would this ever happen? You would have to be incredibly stupid and drunk to have this happen. In this case, casting is not going to save you. If you are stupid enough to malloc this incorrectly in the first place, then the chances are you're going to have screwed up your cast anyway, so there again is no benifit.

    Your argument is absurd, as is your example. I cannot envision this ever possibly happening. By all means, feel free to cast, but there is absolutely no point in ever doing so. Your example is incredibly far fetched. You're basicly saying "Hey, forget that you just declared a variable, and pretend that you think it's some other type!"


    Quzah.
    Hope is the first step on the road to disappointment.

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    int *i = malloc(1);
    And like the other absurd example given for reasons to typecast, only a fool would do this. And, just like the other example, there is no point to type casting this mistake, because with or without the typecast, you still end up with incorrect code and the type cast has no effect what so ever. Neither one produces an error. Neither one produces a warning. Neither one will fix your broken code. Like I've said: There is no reason to ever cast malloc. The only remote examples provided are so absurd they'd never happen in real life, or if they did, they'd happen by a total novice coder who wouldn't benifit either way from the cast, or without it.

    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    Registered User
    Join Date
    Dec 2001
    Posts
    88
    int* p;

    p=(char*)malloc(100);

    so what? Compiler says: failure!
    But what is the benefit?

    It's a false sense of security:
    p=(int*)malloc(100);

    The compiler don't say anything - but it's also wrong...
    What does it help?

    If you don't know which type p is, you are completly lost.

    I don't want to discuss such things. Go and read K&R. Do they cast?? Or look for other gurus! They will tell you all the same.

    The only reason why one casts a void* is to keep compability with C++, there is no other reason.
    Hope you don't mind my bad english, I'm Austrian!

  14. #14
    Registered User
    Join Date
    Dec 2001
    Posts
    88
    It's funny to read...

    I think noone will change their minds, so why discussing?

    I (and as I see some others) keep doing it like the gurus, and you JoeSixpack keep casting.

    I have learned that it is possible to program in a different style as the gurus, but I got to know, that it is somehow easier when you do what the gurus tell you
    Hope you don't mind my bad english, I'm Austrian!

  15. #15
    Registered User
    Join Date
    Feb 2002
    Posts
    6

    Red face realloc

    By the way, can any body expain how to use realloc() function, and it is better to use a example.
    Thanx for help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc casting - quote from the FAQ
    By salvadoravi in forum C Programming
    Replies: 16
    Last Post: 12-17-2007, 06:24 PM
  2. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM
  5. FAQ: Casting malloc?
    By Simon in forum FAQ Board
    Replies: 44
    Last Post: 10-08-2002, 02:25 AM