Search code examples
cstringpid

Converting pid_t to string


I am trying to convert a pid into a string. I tried it this way:

int pid = getpid(); //this int conversion should be ok as far as I know
char * mypid = (char *)malloc(sizeof(int));
sprintf(mypid, "%d", pid);

I assume that my mistake is maybe that I have not added a NULL in the end. I tried to do that but still got error messages. Can someone explain me what is the best way to but a PID into a char * ("string") ? Thanks!!


Solution

  • sizeof(int) is most likely 4 bytes on your system. A string containing a PID will need (assuming a 16 bit PID) at least 6 bytes: 5 for decimal digits and 1 for the null terminator. So you're not allocating enough space and potentially writing past the end of the allocated array. This invokes undefined behavior.

    Make sure you allocate enough space for the string in question:

    int pid = getpid();
    char * mypid = malloc(6);   // ex. 34567
    sprintf(mypid, "%d", pid);
    

    Or use a fixed size string:

    int pid = getpid();
    char mypid[6];   // ex. 34567
    sprintf(mypid, "%d", pid);
    

    If your system supports 32 bit PIDs, you'll need at least 11 bytes. For 64 bit PIDs, at least 21.