02.03.2014 Views

BSP Developer's Guide

BSP Developer's Guide

BSP Developer's Guide

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

VxWorks 5.5<br />

<strong>BSP</strong> Developer’s <strong>Guide</strong><br />

Avoid alloca( ) Function<br />

Many compilers support the alloca( ) function as an extension to the C language.<br />

This normally allocates storage from the stack, as any declared variable would.<br />

Since the storage area is on the stack, this area does not need to be freed, as the<br />

stack is restored upon exiting the function.<br />

While alloca( ) is widely used in code from other OS programming models, it does<br />

not suit VxWorks very well. While other OSs may support automatic stack<br />

expansion and stack checking, VxWorks does not. In embedded programming,<br />

predictable timing and stack usage can be very important. Code for VxWorks<br />

should definitely avoid the use of the alloca( ) function. Allocate the storage<br />

directly on the stack, or use malloc( ) and free( ) if necessary.<br />

Take Care with void Pointer Arithmetic<br />

It is common to use pointer arithmetic on void pointer data types. Because the size<br />

of a void item should be unspecified, the ANSI standard does not allow this<br />

practice. The GNU compiler, however, did allow it and assumed the data size to be<br />

one byte, the same as a char data type.<br />

For example, the following code fragment is faulty:<br />

{<br />

void * pVoid;<br />

pVoid += 1; /* WRONG */<br />

pVoid++; /* WRONG */<br />

pVoid = pVoid + sizeof(char); /* WRONG */<br />

}<br />

The example above is faulty because ANSI pointer arithmetic is based on the size<br />

of the object pointed to. In the case of a pointer to a void, the size is undefined. For<br />

the first faulty statement in the example above, the only correct implementation is<br />

as follows:<br />

{<br />

void * pVoid;<br />

pVoid = (char *)pVoid + 1; /* RIGHT */<br />

(char *)pVoid++; /* WRONG */<br />

(char *)pVoid += 1 /* WRONG */<br />

}<br />

166

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!