Include Include Include Include Include Include Include Int Main Int Fd 1 Char Line 1024 S Q37291424

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(){
        int fd = -1;
        char line[1024];
        size_t bytes_read;
        int pid =0;
        char *match;
        fd =open(“/proc/self/status”, O_RDONLY);
        if(fd == -1){
               printf(“Falure to open”);
        }
        bytes_read =read(fd,line,1);
        line[bytes_read]=”;

       match=strstr(line,”Pid”);
        if(match == NULL){
              
              
        }
        sscanf(match,”cpu MHz :%d”, &pid);// Causing a segment fault

I do not know why my sscanf() is causing a segment fault.


Answer


–> bytes_read = read(fd,line,1);

here you are reading only 1 character that’s why it is givingsegmentation fault.

you have to read full line change the value 1 to 1024.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.