关于网友提出的“ main函数最后一行报Segmentation fault: 11,什么原因?”问题疑问,本网通过在网上对“ main函数最后一行报Segmentation fault: 11,什么原因?”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: main函数最后一行报Segmentation fault: 11,什么原因?
描述:
int main(int argc, char* const argv[]) {
// opt parse
struct ColorHistOptions colorHistOptions = get_option(argc , argv);
std::uint16_t* hist = new std::uint16_t[hash_length]();
switch(colorHistOptions.command){
case MAKELIB:{//lib
std::ofstream binfile_w("./hist.bin", std::ios::out|std::ios::binary);
std::ofstream idxfile_w("./hist.idx", std::ios::out|std::ios::binary);
glob_t buf;
const char * glob_pattern = strcat(colorHistOptions.lib, "/*");
glob(glob_pattern, GLOB_NOSORT, NULL, &buf);
uint i=0;
for(; i < buf.gl_pathc; i++){
try{
idxfile_w << buf.gl_pathv[i] << std::endl;
image_color_hist(buf.gl_pathv[i], size, hist);
binfile_w.write((char *) hist, hash_length*2);
}
catch(...){
printf("buf.gl_pathv[%d]= %s ERROR \n", i, (buf.gl_pathv[i]));
}
}
printf("end glob\n");
globfree(&buf);
printf("free glob\n");
binfile_w.close();
idxfile_w.close();
printf("file close\n");
break;
}
case COSDIST:{//cos
printf("cos\n");
double cos = 0.0;
double score = 0.0;
std::uint16_t* sample_hist = new std::uint16_t[hash_length]();
image_color_hist(colorHistOptions.sample, size, sample_hist);
struct stat statbuf;
if (stat("./hist.bin", &statbuf) == -1) {
/* check the value of errno */
}
int size = (int) statbuf.st_size;
std::uint16_t value = 0;
std::ifstream binfile_r("./hist.bin", std::ios::in|std::ios::binary);
char * buffer = new char[2];
for (int j=0; j<(size/hash_length/2); j++){
for (char i=0; i<>
binfile_r.read(buffer, 2);
value = char2short(buffer);
hist[i] = value;
}
cos = cosDistance(sample_hist, hist);
score = std::max(score, cos);
}
binfile_r.close();
printf("%0.2f", score);
/*
if (score >= 0.9){//append lib
std::ofstream binfile_w("./hist.bin", std::ios::out|std::ios::binary|std::ios::app);
binfile_w.write((char *) sample_hist, hash_length*2);
binfile_w.close();
}
*/
break;
}
case HELP:
default:{
printf("help\n");
std::printf("cosWithLib -c buildLib -l \n");
std::printf("cosWithLib -c cosDist -s \n");
std::printf("cosWithLib -c help\n");
break;
}
}
printf("end switch\n");
return 0;
}
执行之后输出
end glob
free glob
file close
end switch
Segmentation fault: 11
环境:mac
我不能理解的是在最后的return 0上出错,但是我也没找到有什么资源没释放,不知道这个Segmentation fault怎么来的,怎样可以消除
解决方案1:std::uint16_t* hist = new std::uint16_t[hash_length]();
这个没释放
解决方案2: std::uint16_t* hist = new std::uint16_t[hash_length]();
std::uint16_t* sample_hist = new std::uint16_t[hash_length]();
char * buffer = new char[2];
上面这几处是什么时候释放的呢?
解决方案3: 进程意外退出会在当前目录下产生‘core’文件或形如‘core.数字’的文件比如‘core.1234’
使用命令
gdb 运行程序名 core或core.数字
进入gdb然后使用bt命令
可以查看进程意外退出前函数调用的堆栈,内容为从上到下列出对应从里层到外层的函数调用历史。
如果进程意外退出不产生core文件,参考“ulimit -c core文件最大块大小”命令
以上介绍了“ main函数最后一行报Segmentation fault: 11,什么原因?”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/4484762.html