user26775248
user26775248

Reputation:

Unexpected Behavior When Using Optional Arguments in Function

I'm experiencing an issue with sending AT commands through a serial port in my code. The problem is that when I send the following commands:

while (true) {
    thread_sleep_for(5000);

    sendATCommand("AT+CIPSENDEX=0,64");
    sendATCommand("test\\0");
}

The TCP receiver ends up receiving the string AT+CIPSENDEX=0,64 along with test.

To make it more clear: The expected behavior on TCP receiver is:

test

However, current behavior is:

AT+CIPSENDEX=0,64
test

When I did some further testing, I noticed some strange behaviour; when I uncomment a printf statement in sendATCommand, the issue seems to be resolved, and the TCP receiver only gets test:

Here's the relevant code for the sendATCommand function:

void sendATCommand(const char* command, ...) {
    char fullCommand[256] = {0};
    va_list args;
    va_start(args, command);

    vsnprintf(fullCommand, 256, command, args);
    va_end(args);

    // Uncommenting the following line magically fixes the issue:
    // printf("the command is: %s\n", fullCommand);

    strcat(fullCommand, "\r\n"); // Append carriage return and newline
    serial_port.write(fullCommand, strlen(fullCommand));
}

Questions:

Thank you for your help!

Upvotes: 1

Views: 70

Answers (0)

Related Questions