XazGreatXia 2024-08-07 15:53 采纳率: 29%
浏览 6

C语言Segmentation fault (core dumped)问题


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "ext/getinfo.h"
struct System {
    char *hostname;
    char *arch;
    struct CPU *cpu;
    struct MEM *mem;
    char *public_ipaddress;
};
struct CPU {
    char *type;
    int num;
};
struct MEM {
    double totalmem;
    double freemem;
    double availablemem;
    double cache;
};
void getsysinfo() {
    struct System sys;
    sys.hostname = gethostname();
    sys.arch = getarch();
    sys.public_ipaddress = getpublicipaddress();
    sys.cpu->type = getcputype();
    sys.cpu->num = getcpunumber();
    sys.mem->totalmem = getmemtotal();
    sys.mem->freemem = getmemfree();
    sys.mem->availablemem = getmemavailable();
    printf("----Hostname----\n");
    printf("%s\n",sys.hostname);
    printf("----Architecture----\n");
    printf("%s\n",sys.arch);
    printf("----PublicIPAddress----\n");
    printf("%s\n",sys.public_ipaddress);
    printf("----CpuInfo----\n");
    printf("CPUType: %s\n",sys.cpu->type);
    printf("CPUNumber: %d\n",sys.cpu->num);
    printf("----MemoryInfor----\n");
    int mtotal = getmemtotal();
    int mfree = getmemfree();
    int mavailable = getmemavailable();
    int cache = getcache();
    float s1 = mtotal;
    float s2 = mfree;
    float s3 = mavailable;
    float s4 = cache;
    double mt = s1/1024/1024;
    double mf = s2/1024/1024;
    double ma = s3/1024/1024;
    double mc = s4/1024/1024;
    sys.mem->totalmem = mt;
    sys.mem->freemem = mf;
    sys.mem->availablemem = ma;
    sys.mem->cache = mc;
    printf("TotalMem: %.2f\n",sys.mem->totalmem);
    printf("FreeMem: %.2f\n",sys.mem->freemem);
    printf("AvailableMem: %.2f\n",sys.mem->availablemem);
    printf("Cache: %.2f\n",sys.mem->cache);
    printf("----LocalNetwork----\n");
    getlocalipaddress();
}    



int main() {
    getsysinfo();
    return 0;
} 

img


/home/duser/Pictures/remmina_flexus_139.159.199.19:2340_202487-74948.064529.png

root@server:/data/system-get# cat ext/get
getarch.c        getcpuinfo.c     gethostname.c    getinfo.h        getipaddress.c   getmemoryinfo.c
root@server:/data/system-get# cat ext/getinfo.h 
char *gethostname();
char *getarch();
void getlocalipaddress();
char *getpublicipaddress();
char *getcputype();
int getcpunumber();
int getmemtotal();
int getmemfree();
int getmemavailable();
int getcache();

root@server:/data/system-get# cat ext/getmemoryinfo.c 
#include <stdio.h>
#include <stdlib.h>
#define MEMFILE "/proc/meminfo"

int getmemtotal() {
    FILE *f = fopen(MEMFILE,"r");
    if (f == NULL) {
        printf("Cannot Open FILE");
        exit(1);
    }

    char line[100];
    int memtotal;
    int result;
    while(fgets(line,sizeof(line),f)) {
        if(sscanf(line,"MemTotal\t: %d",&memtotal) != 0) {
            result = memtotal;
            break;
        }
    }

    fclose(f);
    return result;
}

int getmemfree() {
        FILE *f = fopen(MEMFILE,"r");
        if (f == NULL) {
                printf("Cannot Open FILE");
                exit(1);
        }

        char line[100];
        int memfree;
    int result;
        while(fgets(line,sizeof(line),f)) {
                if(sscanf(line,"MemFree\t: %d",&memfree) != 0) {
            result = memfree;
                        break;
                }
        }

        fclose(f);
        return result;
}

int getmemavailable() {
    FILE *f = fopen(MEMFILE,"r");
    if(f == NULL) {
        printf("Cannot open FILE");
        exit(1);
    }

    char line[100];
    int memavailable;
    int result;
    while(fgets(line,sizeof(line),f)) {
        if(sscanf(line,"MemAvailable\t: %d",&memavailable) != 0) {
            result = memavailable;
        }
    }
    fclose(f);
    return result;
}

int getcache() {
    FILE *f = fopen(MEMFILE,"r");
    if(f == NULL) {
        printf("Cannot open FILE");
        exit(1);
    }

    char line[100];
    int cache;
    int result;
    while(fgets(line,sizeof(line),f)) {
        if(sscanf(line,"Cache\t: %d",&cache) != 0) {
            result = cache;
        }
    }
    fclose(f);
    return result;
}



root@server:/data/system-get# 
root@server:/data/system-get# cat ext/getinfo.h 
char *gethostname();
char *getarch();
void getlocalipaddress();
char *getpublicipaddress();
char *getcputype();
int getcpunumber();
int getmemtotal();
int getmemfree();
int getmemavailable();
int getcache();

root@server:/data/system-get# cat ext/get
getarch.c        getcpuinfo.c     gethostname.c    getinfo.h        getipaddress.c   getmemoryinfo.c
root@server:/data/system-get# cat ext/getcpuinfo.c 
#include <stdio.h>
#include <stdlib.h>
#define CPUFILE "/proc/cpuinfo"

char *getcputype() {
    FILE *f = fopen(CPUFILE,"r");
    if (f == NULL) {
        printf("Cannot Open CPUFILE");
        exit(1);
    }

    char line[100];
    char cputype[50];
    char *result;
    while(fgets(line,sizeof(line),f)) {
        if(sscanf(line,"model name\t: %[^+]",cputype) != EOF) {
            result == cputype;
            break;
        }
    }
    return result;
    fclose(f);
}

int getcpunumber() {
        FILE *f = fopen(CPUFILE,"r");
        if (f == NULL) {
                printf("Cannot Open CPUFILE");
                exit(1);
        }

        char line[100];
        char cputype[50];
    int num;
        while(fgets(line,sizeof(line),f)) {
                if(sscanf(line,"model name\t: %[^+]",cputype) != EOF) {
                        num++;
                }
        }

        fclose(f);
        return num;
}


root@server:/data/system-get# cat ext/get
getarch.c        getcpuinfo.c     gethostname.c    getinfo.h        getipaddress.c   getmemoryinfo.c
root@server:/data/system-get# cat ext/getipaddress.c 
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <curl/curl.h>
#include <string.h>
void getlocalipaddress() {
    int sockfd;
    struct ifconf ifconf;
    struct ifreq *ifreq;
    char buf[512];

    ifconf.ifc_len = 512;
    ifconf.ifc_buf = buf;

    if((sockfd = socket(AF_INET,SOCK_DGRAM,0))<0) {
        perror("socket");
        exit(1);
    }

    ioctl(sockfd,SIOCGIFCONF,&ifconf);

    ifreq = (struct ifreq*)ifconf.ifc_buf;
    printf("ifconf.ifc_len: %d\n",ifconf.ifc_len);
    printf("sizeof (struct ifreq): %ld\n",sizeof(struct ifreq));

    for(int i = (ifconf.ifc_len/sizeof (struct ifreq)); i>0;i--) {
        if(ifreq->ifr_flags == AF_INET) {
            printf("Network: %s\n",ifreq->ifr_name);
            printf("LocalAddr: %s\n",inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr));
            ifreq++;
        }
    }
}

size_t write_data(void *ptr,size_t size,size_t nmemb,void *stream) {
    if(strlen((char *)stream) + strlen((char *)ptr) > 100000) return 0;
    strcat(stream,(char *)ptr);
    return size *nmemb;
}
char *getpublicipaddress() {
    CURL *curl;
    CURLcode res;
    static char result[100000];
    static char failed[] = "failed";
    curl_global_init(CURL_GLOBAL_DEFAULT);

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl,CURLOPT_URL,"ifconfig.me");
        curl_easy_setopt(curl,CURLOPT_TIMEOUT,10);
        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,write_data);
        curl_easy_setopt(curl,CURLOPT_WRITEDATA,result);
    }

    res = curl_easy_perform(curl);
    if(res == CURLE_OK) {
        return result;
    } else {
        fprintf(stderr,"There is some error at curl_easy_perform() %s\n",curl_easy_strerror(res));
        return failed;
    }
    curl_global_cleanup();

}

root@server:/data/system-get# cat ext/getmemoryinfo.c 
#include <stdio.h>
#include <stdlib.h>
#define MEMFILE "/proc/meminfo"

int getmemtotal() {
    FILE *f = fopen(MEMFILE,"r");
    if (f == NULL) {
        printf("Cannot Open FILE");
        exit(1);
    }

    char line[100];
    int memtotal;
    int result;
    while(fgets(line,sizeof(line),f)) {
        if(sscanf(line,"MemTotal\t: %d",&memtotal) != 0) {
            result = memtotal;
            break;
        }
    }

    fclose(f);
    return result;
}

int getmemfree() {
        FILE *f = fopen(MEMFILE,"r");
        if (f == NULL) {
                printf("Cannot Open FILE");
                exit(1);
        }

        char line[100];
        int memfree;
    int result;
        while(fgets(line,sizeof(line),f)) {
                if(sscanf(line,"MemFree\t: %d",&memfree) != 0) {
            result = memfree;
                        break;
                }
        }

        fclose(f);
        return result;
}

int getmemavailable() {
    FILE *f = fopen(MEMFILE,"r");
    if(f == NULL) {
        printf("Cannot open FILE");
        exit(1);
    }

    char line[100];
    int memavailable;
    int result;
    while(fgets(line,sizeof(line),f)) {
        if(sscanf(line,"MemAvailable\t: %d",&memavailable) != 0) {
            result = memavailable;
        }
    }
    fclose(f);
    return result;
}

int getcache() {
    FILE *f = fopen(MEMFILE,"r");
    if(f == NULL) {
        printf("Cannot open FILE");
        exit(1);
    }

    char line[100];
    int cache;
    int result;
    while(fgets(line,sizeof(line),f)) {
        if(sscanf(line,"Cache\t: %d",&cache) != 0) {
            result = cache;
        }
    }
    fclose(f);
    return result;
}


请问上面的c代码为什么运行之后Segmentation fault (core dumped),本人实在是找不到原因在哪里,gdb只告诉我getsysinfo()有问题,没告诉我具体在哪里

  • 写回答

1条回答 默认 最新

  • 忽见星光 2024-08-07 23:21
    关注

    上面的C代码有好几处会段错误的地方,getsysinfo()函数中,

    • 问题代码:
      sys.hostname = gethostname();
      
      问题点:getinfo.h中重定义了gethostname(),却没有实现,会段错误;可能本意不是想重定义,只是大小写失误;
      解决:该行代码和getinfo.h将gethostname改为getHostName;
    • 问题代码:
      sys.arch = getarch();
      
      问题点:getarch()中没有return语句,后续打印sys.arch的值时会段错误;
      解决:getarch()中增加return语句;
    • 问题代码:
      sys.cpu->type = getcputype();
      sys.cpu->num = getcpunumber();
      
      问题点:struct System结构体中cpu是指针,没有申请内存就直接访问其对象,会段错误;
      解决:如果结构体保持不变的话,使用前申请内存,例如:sys.cpu = (struct CPU *)malloc(sizeof(struct CPU));
    • 问题代码:
        sys.mem->totalmem = getmemtotal();
        sys.mem->freemem = getmemfree();
        sys.mem->availablemem = getmemavailable();
      
      问题点:mem是指针,没有申请内存就直接访问其对象,会段错误;
      解决:如果结构体保持不变的话,使用前申请内存,例如:sys.mem = (struct MEM *)malloc(sizeof(struct MEM));

    另外,getcpuinfo.c的getcpunumber()中变量num没有初始化就执行num++,也会有问题。
    最后,编译程序可以加上-Wall -Werror编译选项,先优化代码。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 8月7日

悬赏问题

  • ¥20 双硬盘安装Ubuntu后windows 无法挂载硬盘
  • ¥15 下面求极限的步骤哪里不对,正确答案是a1a2…an
  • ¥15 帮我利用jupyter 运行一个正确的代码
  • ¥15 如何使用Gephi软件和Python包中的GephiStreamer交互
  • ¥15 sqlite加密问题咨询
  • ¥15 appdesigner接收不到udp组播的数据
  • ¥15 verilog 非阻塞赋值下的移位拼接错误
  • ¥100 两个按钮控制一个LED
  • ¥15 用C语言写离散数学相关问题
  • ¥30 如何用python的GephiStreamer连接到gephi中,把Python和Gephi的具体操作过程都展示,重点回答Gephi软件的调试,以及如果代码的端口在浏览器中无法显示怎么处理