我正在为在 ARM Cortex M0 上运行的 GSM 调制解调器编写驱动程序。系统上唯一的 UART 用于与调制解调器通信,因此我为记录与调制解调器的 UART 对话所能做的最好的事情是在内存中构建一个字符串并使用 GDB 观察它。
这是我的 UART 日志记录函数。
// Max number of characters user in the UART log, when in use.
#define GSM_MAX_UART_LOG_CHARS (2048)
static char m_gsm_uart_log[GSM_MAX_UART_LOG_CHARS] = "";
static uint16_t m_gsm_uart_log_index = 0;
// Write a character to the in-memory log of all UART messages.
static void gsm_uart_log_char(const char value)
{
m_gsm_uart_log_index++;
if (m_gsm_uart_log_index > GSM_MAX_UART_LOG_CHARS)
{
// Clear and restart log.
memset(&m_gsm_uart_log, 0, GSM_MAX_UART_LOG_CHARS); // <-- Breakpoint here
m_gsm_uart_log_index = 0;
}
m_gsm_uart_log[m_gsm_uart_log_index] = value;
}
// Write a string to the in-memory log of all UART messages.
static void gsm_uart_log_string(const char *value)
{
uint16_t i = 0;
char ch = value[i++];
while (ch != '\0')
{
gsm_uart_log_char(ch);
ch = value[i++];
}
}
如果我在上面显示的行上设置断点,第一次到达时,m_gsm_uart_log_index 已经远远超过 2048。我已经看到 2154 和 2048 到 2200 左右之间的其他一些值。
这怎么可能?没有其他代码在任何地方触及 m_gsm_uart_log_index。
最佳答案
您发生了缓冲区溢出,这可能会破坏 m_gsm_uart_log_index
。
缓冲区结束的检查应该是:
if (m_gsm_uart_log_index >= GSM_MAX_UART_LOG_CHARS) {
...
}
按照目前的情况,m_gsm_uart_log_index
可以达到2048,所以写m_gsm_uart_log_index[2048]
很可能是在m_gsm_uart_log_index
所在的位置存储。
关于c - 此代码段中的索引如何达到 2154? (gcc、嵌入式 C、ARM Cortex M0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23082480/