Curnelious
Curnelious

Reputation: 1

String copy- basics

Is this code good?

void function (char* reqData) {
    char serverData[130]={0};
    uint8_t buffer[128] = {0};
    uint32_t len = wifi.recv(&mux_id, buffer, sizeof(buffer), 100);

    //fill the serverData in some for loop
     for(uint32_t i = 0; i < len; i++) 
           serverData[i]=(char)buffer[i];

    serverData[len ] = '\0';
    strcpy(reqData,serverData);       // * my concern !
}

and in the main , using with :

//some global var
char *incomingData={0};

//then 

function(incomingData);

Its causing me problems that I can't explain (strange crashes on the hardware)

Upvotes: 0

Views: 46

Answers (1)

Giorgi Moniava
Giorgi Moniava

Reputation: 28685

Well here

strcpy(reqData,serverData);       // * my concern !

reqData is pointing to where incomingData is pointing:

char *incomingData={0};

But you have not initialized incomingData properly, it is not pointing to a memory where you can write something. Also ={0} initialization of pointer seems a bit weird to me. You can have it initialized like this below - if you know size in advance.

char incomingData[SIZE] = {0};

Also inside function:

char serverData[130]={0};

serverData has length 130 be careful of buffer overflow, what if on the next lines you receive data that is larger than 130?

Upvotes: 2

Related Questions