-2

What is the difference between following snippets of code?

int main()
{
 int *p;
 p= (int*)malloc(sizeof(int));
}

and

int main()
{ 
 int *p = (int*)malloc(sizeof(int));
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
rdx1994
  • 7
  • 2
  • Welcome to Stack Overflow! [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Nov 02 '16 at 08:15
  • The first is an assignment to `p`. The second is an initialization of `p`. The end result is the same, but there is a semantic difference. – Some programmer dude Nov 02 '16 at 08:17
  • You did understand that this question is unrelated to `malloc`. – Jabberwocky Nov 02 '16 at 08:25
  • 1
    You can write `int *p = malloc(sizeof(*p))` instead, to avoid using `sizeof(int)` and typecast `(int*)`.However, in response to your actual question, there is no significant difference between those two statements. You can use either. – RoadRunner Nov 02 '16 at 08:28
  • 1
    @RoadRunner Since `sizeof` is not a function, the parentheses can be dropped whenever the argument is not a type name. So, it can be `int *p = malloc(sizeof *p);`. – unwind Nov 02 '16 at 08:44
  • Yeah that is true @unwind. Probably the best way to do it. – RoadRunner Nov 02 '16 at 09:40

1 Answers1

4
  • The first snippet is two-step, defining a pointer and then, assigning a valid** value to the pointer.

  • The second snippet declares and initializes the pointer via the call to malloc() in a single step.

In effect, end results of both the snippet are same. It's more about coding standard guidelines for which one to use.

One suggestion though, in case using the first style, consider initializing the pointer to NULL to prevent accidental use of the pointer before the assignment.

That said, please see this discussion on why not to cast the return value of malloc() and family in C..


** [Note]: provided, malloc() success.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I don't get this: _in case using the first style, consider initializing the pointer to NULL to prevent accidental use of the pointer before the assignment_, OP is not using `realloc` (there is no problem using `malloc` with an uninitialized pointer). – David Ranieri Nov 02 '16 at 09:10
  • 2
    @KeineLust: This is a general coding guideline. Usually programs involving pointers and malloc() are more complex and mistakes may arise. – mouviciel Nov 02 '16 at 09:16
  • @KeineLust just to clear up, by saying _use_, i meant _defererence_. Any better? – Sourav Ghosh Nov 02 '16 at 09:48
  • @SouravGhosh, no, is fine, I've misreaded the answer, sorry :( – David Ranieri Nov 02 '16 at 09:57