0

I am reading Programming: Principles and practice using C++ by Bjarne Stroustrup and I got to chapter 27 where I encountered something fishy. It is this line of code:

struct List* lst = (List*)malloc(sizeof(struct List*));

My question is, shouldn't this be written as:

struct List* lst = (List*)malloc(sizeof(struct List));

When I compile the program with the first version, it works fine, but I have seen malloc being used as the second version.

So my question is, which version is correct and what are the differences?

PS: The book is about C++, but this chapter tries to present a way of writing in C. So this is actually a C program.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • As far as idiomatic C++ goes, neither is correct. Because malloc doesn't invoke constructors – StoryTeller - Unslander Monica Feb 27 '17 at 13:05
  • 2
    It seems fishy that the inventor of C++ would write (basically) C code, and C code that might be wrong too. Maybe he wrote the program to give examples of the bad things about C and contrasting it with how it should be written in C++? It's little hard to know for us that don't have the book, or don't have it readily available, since there is no context, just two lines of code that could mean anything. – Some programmer dude Feb 27 '17 at 13:07
  • 1
    @Someprogrammerdude isn't in this case, the first one is plain wrong? Am I missing something too obvious here? – Sourav Ghosh Feb 27 '17 at 13:11
  • @SouravGhosh *Semantically* it's definitely wrong, but it really depends on the size of the structure, and its contents and possible constructors. If `sizeof(List)` happens to be the same as `sizeof(List*)` (unlikely as it is) and it's a POD type, then it will work fine. – Some programmer dude Feb 27 '17 at 13:15
  • 1
    @Someprogrammerdude Agree, but very less likely. Plus, the first one , even if it _works_, displays lack of understanding --> poor programming, don;t you agree? – Sourav Ghosh Feb 27 '17 at 13:16
  • @SouravGhosh Oh yeah, I agree. Which is why I think it seems fishy. Someone like Bjarne Stroustrup would not make such a mistake if it was not on purpose. :) – Some programmer dude Feb 27 '17 at 13:24
  • Casting `void *` in C is strongly discouraged and not ideomatic. And that is about C++, not C apparently. – too honest for this site Feb 27 '17 at 13:49

1 Answers1

1

Rule of thumb: When in confusion, check the data types.

In your case, lst is a pointer, which points to a variable of type struct List. So, the memory location required to hold a struct List would be sizeof(struct List). So, the second version makes sense.

P.S.: Congratulations, you thought correct :)

It also appears, List is also defined to be a typedef, otherwise the cast is a syntax error.


NOTE:

In case this code is to be taken as a C snippet, please see this discussion on why or why not to cast the return value of malloc() and family in C..

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261