Thread: quick malloc question

  1. #1
    Registered User
    Join Date
    Mar 2005

    quick malloc question

    I jsut have a question concerning malloc and how exactly is best to use it.

    I've created some variables for example:

    typedef struct tagVector3{
    	float x,y,z;
    typedef struct tagSomething{
    	Vector3 *position;
    when creating the variable "Something" what I would normally do would malloc Something and then malloc the Vector3 variable "position" within it. I've never known if this is the correct way, but always had the nagging feeling it wasn't, so does anyone have an answer?

    Hope this makes sense and thanks for any help,


  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Sydney, Australia
    Your code above declares two typedef aliases to structs, it doesn't actually create variables.

    You could create an instance of the Something type with:
    Something foo;
    This wouldn't require a malloc except for the position inside:
    foo.position = malloc(n * sizeof *foo.position);
    Where n is the number of "Vector3" things you want to allocate for position to point to. Since it's a position, I'm imagining just one, but then you wouldn't have bothered with a pointer, would you.

    If on the other hand, you declared a pointer to Something, you'd do:
    Something *foo;
    foo = malloc(sizeof *foo);
    foo.position = malloc(sizeof *foo.position);
    Of course, you'd check the return of malloc for NULL in each instance.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Well Something isn't a variable, it's a type (or more specifically a type alias for struct tagSomething)

    So you need to create a variable
    Something foo;

    This in itself does not need a call to malloc, since it isn't a pointer.

    It does however contain a pointer, so allocating memory for that is a good idea, like so
    foo.position = malloc ( 100 * sizeof *foo.position );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question on malloc() and reading strings
    By rockysfr in forum C Programming
    Replies: 2
    Last Post: 09-04-2005, 06:37 PM
  2. Quick Question Regarding Pointers
    By charash in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 11:04 AM
  3. Quick Question on File Names and Directories
    By Kyoto Oshiro in forum C++ Programming
    Replies: 4
    Last Post: 03-29-2002, 02:54 AM
  4. * quick question *
    By SavesTheDay in forum C Programming
    Replies: 3
    Last Post: 03-27-2002, 06:58 PM
  5. Quick question: exit();
    By Cheeze-It in forum C Programming
    Replies: 6
    Last Post: 08-15-2001, 05:46 PM