I am working on a multithreaded program. It’s able to close all the threads properly, however, it segfaults at the end. Through commenting out certain parts of my code, I found that it is within this area of the code that deals with opening/closing a file:
char *pid_fname;
FILE *file;
sprintf(pid_fname, "%s%d%s", "/proc/", pid, "/stat");
file = fopen(pid_fname, "r");
/* code */
fclose(file);
I tried debugging in gdb, however I only get this after printing out ‘where’ after the segfault:
#0 0x2f312f63 in ?? ()
#1 0x74617473 in ?? ()
#2 0xbfaee700 in ?? ()
#3 0xbfaee77c in ?? ()
#4 0x006a7810 in ?? ()
#5 0x00000000 in ?? ()
Can anyone give me some pointers on where to go from here?
You have no backing storage for the file name. You’ve created a pointer but have allocated no space. That means it’s almost certainly pointing somewhere where you don’t want to write to 🙂
Assuming you know the maximum range of a process ID (say 5 digits for example), the simplest fix is something like (and changing the arguments slightly since
/proc/and/statare fixed strings):Otherwise, you’ll need to dynamically allocate enough space based on the actual
pidvalue, and code defensively if you run out of memory.Since systems tend to have a fixed range for process IDs, I’d opt for the fixed size buffer. If you really want to protect from bugs whilst still not worrying about dynamic allocation, you could use something like: