I read a sample code from a development kits. The global array is declared without indicating the array size. I wonder is it safe?

Here is the code:

#include <stdio.h>                                           // For Used Function printf 

// UART Buffer
char uart0_buf[];                                           // "sprint" UART[0] Buffer
char uart2_buf[];                                           // "sprint" UART[2] Buffer
char uart3_buf[];                                           // "sprint" UART[3] Buffer


int main()
{
  // UART[0] Print String //
  sprintf(uart0_buf,"Testing1234 - Uart 0\n\r");    // Print Message String 

  // UART[2] Print String //
  sprintf(uart2_buf,"Testing1234 - Uart 2\n\r");    // Print Message String 

  // UART[3] Print String //
  sprintf(uart3_buf,"Testing1234 - Uart 3\n\r");    // Print Message String 
}

Recommended Answers

All 3 Replies

I wonder is it safe?

As written it won't compile, so if you want to get technical it's perfectly safe as it'll never run. However, I suspect that you're paraphrasing. If definitions of those arrays are provided somewhere else then the code will compile and run.

Assuming a more complete example, it isn't necessarily safe because there are no provisions to avoid overflowing the arrays with a string that's too long. This is a classic problem with sprintf(), and the usual answer is snprintf(). However, snprintf() isn't a standard function prior to the C99 standard, so your compiler may not support it.

The problem is it is able to compile. I'm design for embedded the toolchain is Code Red MCU Tools (NXP). I searched every files and can't find any definitions at other files.

Nevermind. I try email NXP. May be their compiler support this feature.

Nevermind. I try email NXP. May be their compiler support this feature.

That seems best. If there are no definitions anywhere then you may be dealing with a compiler extension where an empty array size defaults to something.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.