由free或malloc引起的分段错误?

时间:2017-02-18 03:34:06

标签: c segmentation-fault

我开始编写一些代码(见下文),当我尝试运行它时(gcc file.c; ./a.out)我遇到了一个段错误,我不明白为什么。如果我发表评论

free(filename); // or
double *data = ...;

没有段错误。发生了什么事?我不知道要搜索什么,但我发现了this问题并在第三个答案中遵循了GDB说明。我不理解输出(我从未使用过GDB或任何其他调试器),但也许你这样做。 (gdb)r

Program received signal SIGSEGV, Segmentation fault.│
0x00007ffff7a97d3c in __GI___libc_free (mem=0x7fffffffe5a0) at malloc.c:2945
2945    malloc.c: No such file or directory.

(gdb)bt

#0  0x00007ffff7a97d3c in __GI___libc_free (mem=0x7fffffffe5a0) at malloc.c:2945
#1  0x00000000004006a5 in main ()

哦,取消arg_handler并没有什么不同。

编辑:代码:

//#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//#include "graphics/graphics.c"
//#include "file_operations/file_operations.c"

#define ARGS 6
#define EPS 1e-03
#define DATA_LEN 5

int arg_handler(int ac, char *args[], int *a, char *b, int *c, double *d, double *e, int *f);

int main(int argc, char *argv[]) {

  int N, nsteps, graphics;
  char *filename;
  double dt, theta_max;
  if (arg_handler(argc, argv, &N, filename, &nsteps, &dt, &theta_max, &graphics)) {
    printf("Usage: ...\n");
    free(filename);
    return -1;
  }

  if (graphics) {
    printf("Graphics not available.\n");
    graphics = 0;
  }

  double *data = malloc(N*DATA_LEN*sizeof(double));
/*
  if (read_doubles_from_file(N*DATA_LEN, data, filename)<0) {
    perror("An error occured:\n");
    return -1;
  }
*/

//  free(data);

  return 0;
}

int arg_handler(int ac, char *args[], int *a, char *b, int *c, double *d, double *e, int *f) {

  if (ac!=1+ARGS) {
    return 1;
  }
  *a = atoi(args[1]);
  b = args[2];
  *c = atoi(args[3]);
  *d = atof(args[4]);
  *e = atof(args[5]);
  *f = atoi(args[6]);
  return 0;
}

1 个答案:

答案 0 :(得分:1)

您的free(filename)来电没有相应的malloc()来电; filename指针来自参数向量。这个内存不必释放,并在启动进程时由操作系统管理。

基本上,你的过程是试图释放os拥有的内存;因此,操作系统会阻止你这样做,并向你发出信号。

 // (1) >> unitialized pointer, cannot be freed.
 char *filename;

 double dt, theta_max;
 if (arg_handler(argc, argv, &N, filename, &nsteps, &dt, &theta_max, &graphics)) {
     printf("Usage: ...\n");
     // (3a) >> freeing memory owned by the os.
     // (3b) >> or freeing uninitialized pointer.
     free(filename);
     return -1;
 }

int arg_handler(int ac, char *args[], int *a, char *b, int *c, double *d, double *e, int *f) {
    if (ac!=1+ARGS) {
        // (2b) >> never initializing pointer
        return 1;
    }

    *a = atoi(args[1]);
    // (2a) >> setting value to a pointer managed by the os.
    b = args[2];
    *c = atoi(args[3]);
    *d = atof(args[4]); 
    *e = atof(args[5]);
    *f = atoi(args[6]);
    return 0;
}