I’ve the following piece of code and I think it can cause an overflow in the readlink() function.
pid_t get_pid_from_proc_self()
{
char buffer[4];
pid_t pid;
readlink("/proc/self", buffer, sizeof(buffer));
sscanf(buffer, "%d",(int *)&pid);
return pid;
}
Since the PID is 4 bytes in Linux, readlink() copies 32 bits from “/proc/self” into target[]. Then, according to me, an extra byte should be used for '\0', which makes it 5 bytes.
Also, does readlink() automatically inserts '\0' at the end if string or do I have to specifically assign it to the last byte?
readlink won’t overflow because it doesn’t put the ‘\0’ on the end. But the sscanf will. You should do this:
You should do this: