r/ProgrammerHumor 2d ago

Meme bugIntroducedDebugging

Post image
1.1k Upvotes

120 comments sorted by

View all comments

44

u/PR8-E 2d ago

int* x = (int*) malloc(sizeof(int)); Since malloc returns void pointer you should parse it to type you use.

35

u/yjlom 2d ago

void * coerces to any pointer type. This is valid: int *x = malloc(sizeof(int));. This is also valid (in C23): auto x = (int *) malloc(sizeof(int));.

34

u/Mateorabi 2d ago

Get off my lawn with your newfangled auto keyword. 

7

u/ibevol 2d ago edited 2d ago

Cringe. It’s fine to use auto when the type is clear on the same line. In c++ the following is idiomatic:

auto ptr = std::make_unique<int>(42);

over specifying int twice

std::unique_ptr<int> ptr = std::make_unique<int>(42);

However, the following should not be considered idiomatic:

auto ptr = get_ambiguous_pointer();

It’s the same principle here.