This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

String vs. stack problem

Other Parts Discussed in Thread: EK-TM4C1294XL

I do have a EK-TM4C1294XL , but this is probably a general C code question, and if I enter that board, I am locked into posting on the board forum!?

I receive command strings by UDP. After handling a command, I return a string consisting of a number of elements stitched together in a new string.

Or in case of an unknown command or some conversion error, I return a Not Acknowleded (NAC).

I have somehow run into a problem. If the return string is too long, my return address on the stack is overwritten!

If the return strings are short enough, everything works for thousands of commands!

void ACK(char Cmd[], char Answ[])
{
    char res[] = "0 ";

    strcat(res, Cmd);
    strcat(res, " ");
    strcat(res, Answ);  //If res string ends up too long, return address is overwritten!

    udp_server_send(res);
}


void udp_incomming(void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, u16_t port)
{
    char Command[25];
    char Catch[5], SweepParam[9];
    char Answer[] = "----";
    char b[10];
    unsigned short c;
    int a, i, j;
    uint32_t Cardinal;

    if (p != NULL) {
        memcpy(Command,p->payload,p->len);
        Command[p->len]=0;
        memcpy(Catch,Command,4);
        Catch[4]='\0';
        ConvertError=false;

//Catch is a short string used to figure out which command I have received

---

        if (ConvertError)
            NAC(Command);
        else
            ACK(Command, Answer);

    }

    pbuf_free(p);
}

I am not all that well educated in C, but somehow I should clear more space on the stack, or maybe start using pointers.

But all that 'star'-stuff is still pretty alien to me!

How do I proceed?

  • Changing the Ack routine to:

    void ACK(char Cmd[], char Answ[])
    {
        char res[50] = "0 ";
    
        strcat(res, Cmd);
        strcat(res, " ");
        strcat(res, Answ);  //If res string ends up too long, return address is overwritten!
    
        udp_server_send(res);
    }
    
    

    .. apparently solves the problem. I do not expect returning strings longer than about 30 characters.

    But is that the porper way to do it?

  • Yes, that is the way to do it. In the first example, res will be only as long as the initialization string.

    Are Cmd and Answ properly terminated with '\0'?

    Do you want to send the '0' that you put in the res string? Or is that intended to be a nul terminator to indicate the end of the string?

  • Yes, the "0" (char 0x30) is there for the purpose of indicating a command acknowledge. In the NAC response I have put in a "1" at the start.

    And parameter strings are null-terminated, as is the resulting res.