Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on How to properly use malloc?

Parent

How to properly use malloc?

+10
−0

I have seen this construct quite a lot:

int *p = (int*) malloc(n * sizeof(int));

Is this how it should be? What is the proper way to use malloc? I have also seen this:

int *p = malloc(n * sizeof *p);

Which one is preferable?

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

Post
+6
−0

TL;DR

You should use

int *p = malloc(n * sizeof *p);

for two reasons

  1. The cast (int*) is not necessary, which means it's clutter.
  2. Using sizeof *p instead of sizeof(int) removes code duplication.

But remember to check if allocation succeeded before using the memory. It's done like this:

int *p = malloc(n * sizeof *p);
if(!p) {
    // Handle error
}

Longer answer

1 - Casting

Some people argue that the cast makes it possible to compile the code with both a C compiler and a C++ compiler. While this is technically true and sometimes useful, it's not the typical use case. If you know that you want to be able to do this, then cast. A C++ compiler will throw a compiler error if you don't.

But in C, a void pointer (malloc returns a void pointer[1]) can safely be implicitly casted to any other pointer type and back. So it is completely safe to omit it. Note that this is true for void pointers in general. It's not special for malloc. It just happens to be the case that this discussion comes up a lot when talking about malloc.

2 - sizeof

Let's say you have this code:

int *p;
// Many lines of code
p = malloc(size1 * sizeof(int));
// More lines of code
p = malloc(size2 * sizeof(int)); 

Suddenly you realize that you have to change the type of p to another pointer type. Will you remember to change everywhere? And are you sure you will not miss anything? Using sizeof *p eliminates this problem. But do remember that sizeof p is the size of the pointer, that is sizeof (int*). Mixing this up might give you annoying and hard traced bugs.

If you have a pointer to pointer to create a 2D structure, the pattern is like this:

int **p;
p = malloc(x * sizeof *p);
for(int i=0; i<x; i++) 
    p[i] = malloc(y * sizeof *p[i]);

If you're dealing with pointers to arrays, you might want to be a bit careful. Especially if they are arguments to functions. For instance, int a[5][5] means different things if it is declared as an argument or in function body or global space. If declared in function body or global space, that will give you a two dimensional 5x5 array. But if declared in a function argument, it will be a pointer to one dimensional 5 array. The equivalent declaration is int (*a)[5].

There is also the case with flexible array members of a struct, but IMO it's pretty obvious that this method does not work flawlessly there. It also does not work for void pointers, because they cannot be dereferenced.

Read more about when this work and not here

More opinionated stuff

Other argue that "it's good habit" to add that extra check that the cast gives. It forces you to think one more time. I strongly disagree with this for several reasons.

Firstly, you very rarely do this for non-pointer types. This code looks completely ridiculous:

signed char x = (signed char)42;
long y = (long)x - (long)8;

Do note that these casts do have their uses. What I'm saying is that it is a bad thing to blindly throw them in everywhere without even knowing why or if it's needed.

Secondly, in C a cast typically means "I know what I'm doing". So if you're doing it wrong, you can actually HIDE a bug. The argument about forcing you to think again makes sense in C++, because it will not compile if you do it wrong.


  1. In early C, before the 89 standard, there was no void pointer. Instead, a char pointer was used. That's over 30 years ago. ↩︎

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

3 comment threads

The difference between (int*)malloc and (int)42 (7 comments)
Pre-C89 `malloc` return type (3 comments)
The forgetting stdlib.h argument (2 comments)
The difference between (int*)malloc and (int)42
Lundin‭ wrote over 2 years ago

The difference between (int*)malloc and (int)42 is that malloc does actually return a different type. In your integer examples, the type is already the expected int. Furthermore, the C language does actually not allow any implicit pointer conversions except during pointer assignment. 6.5.4 Conversions that involve pointers, other than where permitted by the constraints of 6.5.16.1, shall be specified by means of an explicit cast. (6.5.16.1 being the rules of assignment). C is however happy to do all manner of wild & dangerous implicit integer conversions though.

klutt‭ wrote over 2 years ago

I updated to a better example

Lundin‭ wrote over 2 years ago

Expect casting to the expected type is a common way to dodge implicit promotions, so doing so might actually be considered good practice depending on context. For example MISRA-C wouldn't allow this code unsigned short a,b; ... signed int c = a + b; but require c = (signed int)(a + b). Though this code still contains the implicit promotion and only counters it after it happened - to actually prevent it, you'd have to cast each operand: (signed int)a + (signed int)b. Yeah this is a bit silly when doing simple stuff like addition, but not so much when dealing with various bitwise operators, where signed operands can create all manner of bugs.

alx‭ wrote over 2 years ago · edited over 2 years ago

@Lundin Good news for unsigned short (and in general for uintN_t shorter than int): unsigned _BitInt(N) from C2x will not promote to int (the same applies to signed shorts, but bitfields tend to be unsigned). So you won't need to clutter bitwise operations with casts all around.

Lundin‭ wrote over 2 years ago

alx‭ Really? I haven't heard about that and the C committee hates fixing language flaws at the expense of backwards compatibility. Such a radical change would be nice but it also means that all C code out there won't be compatible with C2x.

klutt‭ wrote over 2 years ago

Lundin‭in "Depending on the context" is my exact point. You don't throw them in everywhere just for the sake of it.

alx‭ wrote over 2 years ago · edited over 2 years ago

@Lundin they didn't break backwards compatibility. They added an entirely new set of integer types in parallel to the old one, which is still supported with its buggy design. It's not yet sure if it'll make it into C2x, but Clang supports it, and GCC has an open bug to add support for it. Anyway, it'll probably be in C3x if it does not make it into C2x. See also: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102989, http://www.open-std.org/JTC1/SC22/WG14/www/docs/n2763.pdf