Thread: a couple of malloc problems

  1. #1
    Registered User
    Join Date
    Mar 2016
    Posts
    6

    a couple of malloc problems

    hi,

    i have 2 problems with using the malloc function:

    1.
    Code:
    int listValues[count] = malloc(count*sizeof(int));
    the error i get: "variable-sized object may not be initialized"

    2.
    Code:
    Node node3 = malloc(sizeof(*Node));
    the error i get: "expected expression before 'Node'"

    how i defined Node:

    Code:
    typedef struct node_t* Node;
    struct node_t {
    	int data;
    	Node next;
    };
    can someone help me solve these errors?

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    1. A variable-length-array (a C99 (mis)feature) does not require a malloc (or associated free). They are automatically allocated and freed at runtime.

    2. The error is referring to the second occurrence of Node in the statement where you are attempting to dereference a typedef. That doesn't work. You can fix it in two ways. Either change your typedef so that Node is not a pointer to node_t (we usually recommend that you not hide the fact that something is a pointer behind a typedef), or use the variable name in the sizeof, like sizeof(*node3).

  3. #3
    Registered User
    Join Date
    Mar 2016
    Posts
    6
    thanks, had no idea about this C99 feature! =)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with malloc
    By Zachary Lewis in forum C Programming
    Replies: 7
    Last Post: 02-18-2008, 06:45 AM
  2. couple problems with structures
    By DLR in forum C Programming
    Replies: 15
    Last Post: 04-06-2006, 08:40 PM
  3. malloc problems
    By garion in forum C Programming
    Replies: 5
    Last Post: 12-30-2005, 03:57 PM
  4. Replies: 17
    Last Post: 03-03-2005, 06:47 PM
  5. Malloc problems
    By PunkyBunny300 in forum C Programming
    Replies: 5
    Last Post: 10-01-2003, 07:27 PM