tags:

views:

194

answers:

4

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);
+12  A: 

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.

James McNellis
As a follow-up on this, since `malloc` needs to go find available memory on the heap, a semaphore is usually taken. This results in a possible problem if this code lives in an ISR or other critical section. Using the stack is considerably faster, since the compiler just does "allocations" as a single addition to the stack pointer, which also means there's no lock to worry about.
jheddings
+5  A: 

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.

Moishe
+3  A: 

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.

rmn
+1  A: 

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.]

Lee-Man