Domanda

Suppose I have the following function signature:

int printf(const char * restrict format, ... );

Now, I have a string defined as follows:

volatile char command_str[256];

Now, when I want to pass this string to my printf function, I will get the following warning:

Warning 32  [N] 2943 : passing 'volatile char [256]' to parameter of type 'const char *' discards qualifiers    C:\P\parameter\parameter.c

I do not want to change the printf signature, the easiest solution to make the warning go away would be

printf((const char*)command_str, .......);

I have a feeling that this is not the best solution. What would be the correct thing to do? I cannot make command_str non-volatile since it is accessed within an interrupt.

È stato utile?

Soluzione

the const in printf()'s signature declares a promise printf() makes -- it won't mess with the data pointed to by format (therefore, both char* and const char* variables may be passed in for format).

Now, your array is volatile (and I expect you know the implication of that). The compiler warns you, that this volatility is discarded in printf()'s scope -- you won't get volatile semantics for accesses to format within printf().

As a suggestion what to do, I'd say evaluate whether you really want changes to the data be apparent midst- printf(). I can't see a reason for wanting that, so making a local copy sounds reasonable.

Altri suggerimenti

The function are are passing to (printf()) expects the string to be mutable (const * means that printf() will not modify the content, not to be confused!), and the string you are trying to pass will get modified (well, to be precise the pointer to the string) by an interrupt.

How can you be you be sure that an interrupt will not modify the contents of the string between you calling printf() and printf() actually printing...? What prevents the interrupt from happening while printf() is working?

You need to mask interrupts while calling printf() (using ASM {"CLI"} or something more applicable to your platform), or just copy the string you pass to printf():

// point a
char s[256];
strncpy(s, command_str, 256);
// point b
printf("%s", s);
// point c

This will fix the problem for printf(), but now you have a new race condition point a and b. I think you need to refactor your code. You have bigger issues.

One solution might be:

char s[256];
mask_interrupts();
strncpy(s, command_str, 256);
unmask_interrupts();
printf("%s", s");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top