Search code examples
cmisra

Store pointer to array in file scope from array paramter in a function


I am rebuilding an application to comply with MISRA-rules and using QA-C to analyze my code.

One of those annoying rules involve pointers and arrays. You can't say:

char foo[10];
char * bar = &(foo[0]);

bar[5] = 'a';

Nor can you then do:

*bar = 'a';
bar++;

My problem involves two functions and a file-scope variable.

Originally this code did the following (bit-pseudocode-like):

static char * bufferPtr;

static void foo_a(char * buffer /* other params */)
{
    bufferPtr = buffer;

    /* some logic goes here */
    switch()
    {
        case 'b':
           foo_b(/* some param */);
}

static void foo_b(/* parameters */)
{
    if (/*something*/)
    {
        /*  some logic */
        foo_c(/* data-param */);
        /* some logic */
    }
    else
    {
        /*  some logic */
        foo_c(/* data-param */);
        /* some logic */
    }
}

static void foo_c(char data)
{
    *buffer++ = data;
}

I've tried to rewrite it to the following:

static char (*bufferPtr)[];
static char bufferIndex;

static void foo_a(char buffer[] /* other params */)
{
    bufferPtr = &buffer;
    bufferIndex = 0;

    /* same */
}

static void foo_b(/* parameters */)
{
    /* same */
}

static void foo_c(char data)
{
    (*bufferPtr)[bufferIndex] = data;
    bufferIndex++;
}

But then both misra and my compiler (softune, by Fujitsu) complain. Compiler says:

assignment incompatible pointer types from CHAR **' toCHAR (*)[]': operator `='

Misra says:

[C] Right operand of assignment is not of compatible pointer type. Address of automatic object exported to a pointer with linkage or wider scope.

However I do need to be able to index an array in the foo_c function. Or are there other ways to and follow misra and make my code work.

If I do the following in the same file:

static CHAR foo[10];
static CHAR (*bar)[];
static void f(void)
{
    bar = &foo;
}

Then nor Misra nor my compiler complain about anything.


Solution

  • I've changed the flow of this code to just pass the buffer parameter to each subsequent version.

    It is ugly, but it works and is somewhat safe. 'according to misra'