Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting pid_t to string

Tags:

c

string

pid

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!!

like image 464
wolverine Avatar asked Dec 13 '22 14:12

wolverine


2 Answers

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.

like image 96
dbush Avatar answered Dec 24 '22 06:12

dbush


The mypid character array is not of the correct size. You are using sizeof(int) which is the number of bytes necessary to hold an integer on your system, not the string length of the integer. You could either count the number of digits if you want to be exact, or allocate a buffer of sufficient size, if exact storage is not a concern.

Correct and safe would be:

const size_t max_pid_len = 12; // Could be system dependent.
int pid = getpid();
char * mypid = malloc(max_pid_len + 1);
snprintf(mypid, max_pid_len, "%d", pid);
like image 27
Blunt Jackson Avatar answered Dec 24 '22 08:12

Blunt Jackson