[英]How can i fix segmentation fault(core dump)?
#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(eg)) 中。
我不知道如何使用 gdb 调试此代码。 当我输入“gcc -g -o test cache_proxy.c”时,它不返回测试文件。 所以我找不到问题线。
请告诉我。
如何修复分段错误(核心转储)?
例如,您可以通过不使用未初始化的指针来解决此问题
char* input_url;
…
scanf("%s",input_url);
通过在编译命令中添加-Wall
并删除您收到的警告的来源,可以避免此类错误。 此后您可能不需要调试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.