1
\$\begingroup\$
   char fromBluetooth[] = "zgr\r123\r";
   int name_length = 0;
    int pass_length = 0;

    while (1)
    {
        if (fromBluetooth[name_length] == '\r')
        {
            break;
        }name_length++;
    }

    char ssid_determined[name_length];

    for (int i = 0; i < name_length; i++)
    {
        ssid_determined[i] = fromBluetooth[i];
    }

    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(ssid_determined);

This code should give a result on LCD as "zgr", but what I am getting on LCD is "zgr!\r\r". Can someone explain me how does this happen?

NOTE: That lcd object is Arduino's LiquidCrystal type.

\$\endgroup\$
  • 3
    \$\begingroup\$ You need to null terminate ssid_determined. Otherwise it will just continue to print stuff until it happens upon a memory address that is 0. \$\endgroup\$ – Tom Carpenter May 21 '15 at 21:47
9
\$\begingroup\$

First off, I'm not sure how you're declaring an array with a length specified at run-time. This is standard C, right?

What's probably causing your problem is that ssid_determined is not null-terminated. The size of ssid_determined should be name_length + 1, and the final character should be '\0'.

\$\endgroup\$
  • \$\begingroup\$ plus one on the nul-termination. This is the problem. Variable length arrays are introduced in ISO C99, so you can call them standard. \$\endgroup\$ – Eugene Sh. May 21 '15 at 21:21
  • 1
    \$\begingroup\$ Looks like VLAs are optional in C11: groups.google.com/forum/#!topic/comp.std.c/AoB6LFHcd88 . Seems like a questionable feature in an embedded program, but maybe I'm just being old-fashioned. \$\endgroup\$ – Adam Haun May 21 '15 at 21:42
  • \$\begingroup\$ I agree that in embedded dynamic allocations are better to be avoided even on stack. The stack is usually pretty shallow, it's easy to overflow it.. \$\endgroup\$ – Eugene Sh. May 21 '15 at 21:47
  • 2
    \$\begingroup\$ @AdamHaun: They have been a mandatory feature in C99, but since gcc only got them right in around 2010 it was probably a too hard feature to require from everyone. \$\endgroup\$ – PlasmaHH May 21 '15 at 22:00
  • \$\begingroup\$ The advisability of variable length array types (or anythings) basically on Embedded is still somewhat dependent of the quality of the underlying compiler suite. As well, in some cases, the actual hardware. If you're running this on a due-like ARM equipped board using the proper and most recent GCC-based compilers, you won't notice that many performance problems. The real rub in that case starts when you force it to use malloc() type functions rather than "thinking" of something fitting itself. In my Humble Experience, at least. \$\endgroup\$ – Asmyldof May 21 '15 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.