Search code examples
cprintfmallocstrcpykeil

strcpy and strcat in Keil C compiler


I used this code to print some string,but it does not print any thing.
What is the problem?

char* getNotFilledEncryptionParams(void)
{
    char* nofilledStr;
    char tmp[3];
    const char * arr[]= {" P,"," Q,"," A,"," B,"," C,"," R,"," S0,","S1,","S2,","F1,","G1"};


   for(i=0;i<11;i++)
   {
      if(filledParams[i] == 0)
      {
        strcpy(tmp,arr[i]);
        strcat(nofilledStr,tmp);
      }
   }

return nofilledStr;
}

Usage:

int main(void){

    char *remaining;

    remaining = getNotFilledEncryptionParams();
    printf("\r\n Remaining item:%s",remaining);

}

I think the problem is in const char * arr[] and I changed it,but the problem remains.


Solution

    1. You didn't allocate any memory for noFilledStr, so its value is indeterminate and strcat(noFilledStr, tmp) is undefined.

      Use malloc to allocate memory and initialize noFilledStr with the returned pointer:

      char* noFilledStr = malloc(number_of_bytes);
      
    2. The strings in arr are char[4], not char[3] (do not forget the null byte!). tmp is too small to hold them, so strcpy(tmp, arr[i]) writes out of bounds.