0

I keep getting an invalid initializer error in this line:

StackObject_t new = (StackObject_t*)malloc(sizeof(StackObject_t));

The StackObject_t type is defined as such:

typedef struct stackObject* pStackObject_t;
typedef struct stackObject
{
    void* obj;
    pStackObject_t next;
} StackObject_t;

and this is the exact error I get: Error message

kiryakov
  • 145
  • 1
  • 7
  • [Please see this discussion on why not to cast the return value of malloc() and family in C..](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Oct 20 '20 at 12:48
  • 2
    You're assigning a pointer to a thing (`StackObject_t *`) to a thing (`StackObject_t`). Also, recommend not using the variable name `new` because this is a reserved word in C++. This is fully legal in C, but it's a good habit to avoid C++ keywords just to make life easier if/when you step up to C++ – Steve Friedl Oct 20 '20 at 12:49
  • 7
    @SteveFriedl Don't be so pessimistic. Not every C programmer has to step down to C++. – JeremyP Oct 20 '20 at 12:56
  • 3
    Using `new` as identifier is a good way to get a warning if you accidentally put it in a C++ compiler. – Gerhardh Oct 20 '20 at 12:59
  • None the less, syntax formatting IDEs tend to not make a difference between C and C++, as we can see from this SO post. So that alone is a good reason to avoid C++ keywords. – Lundin Oct 20 '20 at 13:00

2 Answers2

4

First of all, you should not cast the result of malloc as it can hide errors and C automatically casts void* to the correct pointer type. Secondly, your issue is because you have StackObject_t as the type of the variable but malloc returns a StackObject_t*. You can fix this by changing your line to StackObject_t* new = ... so the types match up.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • `malloc` returns a `void *`, not `StackObject_t*`. Also, C automatically **converts** `void *` to other pointer types. It is a conversion, which is an operation that is performed. It is not a **cast**, which is an explicit operator in source code. – Eric Postpischil Oct 20 '20 at 13:00
0

It doesn't work for the same reason as int* ptr; int i = ptr; doesn't work. A pointer is not a valid initializer to an int.

The clang compiler gives a better diagnostic:

warning: incompatible pointer to integer conversion initializing 'StackObject_t' with an expression of type 'StackObject_t *'; dereference with * [-Wint-conversion]

Aha, StackObject_t is not compatible with StackObject_t *. You probably meant to write:

StackObject_t* ptr = malloc(sizeof *ptr);

Details: "Pointer from integer/integer from pointer without a cast" issues

Lundin
  • 195,001
  • 40
  • 254
  • 396