I am trying to write a program that extracts information from proc. Right now I am trying to get the processor type from cpuinfo. My code compiles, but I am getting a segfault (core dump). I cannot get lldb to run to debug. Here is my code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
char cpuinfo()
{
char element[400];
FILE* fp;
fp = fopen("/proc/cpuinfo", "r");
int token_count = 0;
if (fgets(element, 400, fp) != NULL)
{
char *token;
token = strtok(element, "\n");
printf("%s\n", token[4]);
}
fclose(fp);
return(0);
}
int main(int argc, char *argv[])
{
printf("Hello world\n");
cpuinfo();
}
You fail to perform any bounds validation. Will token have an element '4'?
printf("%s\n", token[4]);
Try
for ( char *token = strtok( element , "\n" ); token != NULL; token = strtok( NULL, "\n" ) )
{
puts( token );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.