Reputation: 913
Is there any difference between the below two snippets? One is a char array, whereas the other is a character array pointer, but they do behave the same, don't they?
Example 1:
char * transport_layer_header;
// Memory allocation for char * - allocate memory for a 2 character string
char * transport_layer_header = (char *)malloc(2 * sizeof(char));
sprintf(transport_layer_header,"%d%d",1,2);
Example 2:
char transport_layer_header[2];
sprintf(transport_layer_header,"%d%d",1,2);
Upvotes: 1
Views: 860
Reputation: 414
Assuming you correct the "no room for the null" problem, i.e. allocate 3 bytes instead of 2, you would normally only use malloc() if you need dynamic memory. For example, if you don't know how big the array is going to be, you might use malloc.
As pointed out, if you malloc() and don't later free the memory then you have a memory leak.
One more point: you really should check the return value of malloc() to ensure you got the memory. I know that in Solaris malloc() never fails (thought it may sleep -- a good reason not to call it if you don't want your process going to sleep, as noted above). I assume that on Linux malloc() could fail (i.e. if there is not enough memory available). [Please correct me if I'm wrong.]
Upvotes: 1
Reputation: 2426
The most important difference, IMO, is that in the second option transport_layer_header is a const pointer (you can't make it point to a different place), where as in the first option - you can.
This is ofcourse in addition to the previous answers.
Upvotes: 3
Reputation: 8471
The other difference is that your first example will corrupt data on the heap, while the second will corrupt data on the stack. Neither allocates room for the trailing \0.
Upvotes: 5
Reputation: 355049
Yes, there is a difference. In the first example, you dynamically allocate a two-element char array on the heap. In the second example you have a local two-element char array on the stack.
In the first example, since you don't free
the pointer returned by malloc
, you also have a memory leak.
They can often be used in the same way, for example using sprintf
as you demonstrate, but they are fundamentally different under the hood.
Upvotes: 11