c - Not able to read /proc/[pid]/stat in unix showing segmentation fault -


i trying read /proc/[pid]/stat in ubuntu unix.but output comes segmentation fault. passing pid get_usage().

 #include <stdlib.h>   #include <sys/types.h>  #include <stdio.h>  #include <string.h>  #include <unistd.h>  struct pstat { long unsigned int utime_ticks; long int cutime_ticks; long unsigned int stime_ticks; long int cstime_ticks; long unsigned int vsize; // virtual memory size in bytes long unsigned int rss; //resident  set  size in bytes  long unsigned int cpu_total_time;  };   void main(){   int pid_t;    struct pstat *result;   pid_t = getpid();   get_usage(pid_t,result);    }  int get_usage(const pid_t pid, struct pstat* result) {  printf("%d",pid); char pid_s[20]; snprintf(pid_s, sizeof(pid_s), "%d", pid); char stat_filepath[30] = "/proc/";   strncat(stat_filepath, pid_s,sizeof(stat_filepath) - strlen(stat_filepath) -1);  strncat(stat_filepath, "/stat", sizeof(stat_filepath) -strlen(stat_filepath) -1); printf("%s",stat_filepath);  file *fpstat = fopen(stat_filepath, "r");  if (fpstat == null) {     perror("fopen error ");     return -1; }  file *fstat = fopen("/proc/stat", "r"); if (fstat == null) {     perror("fopen error ");     fclose(fstat);     return -1; }   //read values /proc/pid/stat bzero(result, sizeof(struct pstat)); long int rss; if (fscanf(fpstat, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu"             "%lu %ld %ld %*d %*d %*d %*d %*u %lu %ld",             &result->utime_ticks, &result->stime_ticks,             &result->cutime_ticks, &result->cstime_ticks, &result->vsize,             &rss) == eof) {     fclose(fpstat);     return -1; } fclose(fpstat); result->rss = rss * getpagesize();  //read+calc cpu total time /proc/stat long unsigned int cpu_time[10]; bzero(cpu_time, sizeof(cpu_time)); if (fscanf(fstat, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",             &cpu_time[0], &cpu_time[1], &cpu_time[2], &cpu_time[3],             &cpu_time[4], &cpu_time[5], &cpu_time[6], &cpu_time[7],             &cpu_time[8], &cpu_time[9]) == eof) {     fclose(fstat);     return -1; }  fclose(fstat);  for(int i=0; < 10;i++)     result->cpu_total_time += cpu_time[i];  return 0;   } 

output:

    segmentation fault(core dumped) 

code source:https://github.com/fho/code_snippets/blob/master/c/getusage.c

in get_usage() calling bzero() , trying fscanf() using variable called result never allocated memory.

you need make result variable in main() function struct stat result , pass &result get_usage() function.


Comments