Search code examples
cstringstring-concatenation

C : string concatenation of multiple string truncates the portion of string after concatenation


I have to concatenate multiple strings as a single string in c and for the same using the snprintf,

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
  char id[] =  "D0D0-0000-0000-0000-0001-A431";
  char mac[] = "fc017c0f2b75";
  char aid[] = "1";

  printf("size of id :: %ld\n", sizeof(id));
  printf("size of mac :: %ld\n", sizeof(mac));
  printf("size of aid :: %ld\n", sizeof(aid));

  char *uniqueID = (char*)malloc(50);
  snprintf(uniqueID, sizeof(uniqueID), "%s.%s.%s", id, mac, aid);
  printf("uniqueID :: %s\n", uniqueID);
  printf("size of uniqueID :: %ld\n", sizeof(uniqueID));
}

and for the given requirements using the above code, i can able to produce the below result,

size of id :: 30
size of mac :: 13
size of aid :: 2
uniqueID :: D0D0-00
size of uniqueID :: 8

whereas, the required result is,

size of uniqueID :: D0D0-0000-0000-0000-0001-A431.fc017c0f2b75.1

What is an issue here? How to resolve this?


Solution

  • The size you provided for snprintf is incorrect (sizeof(uniqueID) is the size of the pointer = 8). For your case, it should've been:

      snprintf(uniqueID, 50, "%s.%s.%s", id, mac, aid);
    

    Had uniqueID been an array as shown below, your program would've worked alright (sizeof(uniqueID) is the size of the char array = 50) :

      char uniqueID[50] = {};
      snprintf(uniqueID, sizeof(uniqueID), "%s.%s.%s", id, mac, aid);