【问题标题】:How can i fix segmentation fault(core dump)?如何修复分段错误(核心转储)?
【发布时间】:2021-06-23 09:37:38
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
#include <dirent.h>
#include <sys/types.h>
#include <pwd.h>
#include <sys/stat.h>
#include <fcntl.h>

char* sha1_hash(char *input_url, char *hashed_url){
        unsigned char hashed_160bits[20];
        char hashed_hex[41];
        int i;

        SHA1(input_url, strlen(hashed_hex), hashed_hex);
        for(i=0; i<sizeof(hashed_160bits);i++)
        sprintf(hashed_hex + i*2, "%02x", hashed_160bits[i]);
        strcpy(hashed_url, hashed_hex);
        return hashed_url;
}

char* getHomeDir(char *home) {
        struct passwd *usr_info = getpwuid(getuid());
        strcpy(home, usr_info->pw_dir);
        return home;
}

int main()
{
        char* token;             //To use strtok             
        char* input_url;
        char* hash_ptr;
        char hash_name[3], *hash_txt;   
        char* home;
        DIR *Pdir;                            
        int fd;                             

        Pdir = opendir(getHomeDir(home)); 
        if(Pdir == NULL)                       
        {
                printf("Open ERROR\n");        
                return 0;
        }
    
        umask(0000);
        mkdir("cache", 0777);
        do
        {
                printf("input URL>");
                scanf("%s",input_url);
                hash_ptr = sha1_hash(input_url, hash_ptr);

                for(int i=0; i<3; i++)
                {
                        hash_name[i] = hash_ptr[i];
                }

                hash_ptr[2] = ' ';         //To use Strtok

                token = strtok(hash_ptr, " ");
                while(token != NULL)
                {
                        token = strtok(NULL, " "); 
                }
                hash_txt = token;

                umask(0000);
                mkdir(hash_name, 0777);
                fd = open(hash_txt, O_CREAT, 0777);

                closedir(Pdir);
                close(fd);
        }while(strcmp(input_url, "bye"||"BYE") != 0);
}

当这个程序运行时。它制作缓存目录并获取输入(URL链接) 并将 URL 链接转换为 41 范围散列十六进制。数组的前 3 个元素是目录名称(存储在缓存目录中),左侧 38 存储在 (cache/00x(e.g)) 作为文件名。

我不知道如何用 gdb 调试这段代码。 当我输入“gcc -g -o test cache_proxy.c”时,它不返回测试文件。 所以我找不到问题所在。

请告诉我。

【问题讨论】:

  • " 当我输入 gcc -g -o test cache_proxy.c 它不返回测试文件"。 gcc 是否返回任何错误?

标签: linux segmentation-fault


【解决方案1】:

如何修复分段错误(核心转储)?

你可以通过不使用未初始化的指针来解决这个问题,例如

        char* input_url;
        …
                scanf("%s",input_url);

可以通过将-Wall 添加到您的编译命令并删除您收到的警告的来源来避免此类错误。之后您可能不需要调试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2017-04-05
    • 2019-09-03
    • 1970-01-01
    • 2017-07-24
    • 2020-02-04
    • 2015-06-25
    相关资源
    最近更新 更多