接收内存访问错误:两次释放或损坏(出)

时间:2018-09-19 05:05:54

标签: c memory-management

面对相当困惑的问题。我已经在行free('line')之前放置了打印语句,并且似乎声明为char * line的字符数组正在按需打印。

我创建了一个自定义strdupe函数以提高效率。 nthread_lines表示一个字符串数组,其中每行长度是可变的。

下面是相关代码:

#define NUM_THREADS     5

char *strdupe(const char *src) {
    size_t len = strlen(src) + 1;
    char *s = malloc(len);
    if (s == NULL)
        return NULL;
    return (char *)memcpy(s, src, len);
}

int main(int argc, char *argv[]) {
  FILE *stream;
  // holds NUM_THREADS amount of lines read in from file
  char** nthread_lines;

  char *line = NULL;
  size_t len = 0;
  ssize_t nread;

  size_t NUM_THREADS_ctr = 0;
  nthread_lines = malloc(NUM_THREADS * sizeof(char *)); 

   while ((nread = getline(&line, &len, stream)) != -1) {

       nthread_lines[NUM_THREADS_ctr] = strdupe(line);

       printf("Length of buffer %d\n", strlen(nthread_lines[NUM_THREADS_ctr]));
       printf("Size of buffer CHECK %d\n", sizeof(nthread_lines[NUM_THREADS_ctr]));
       printf("Check nthread_lines:%s\n", nthread_lines[NUM_THREADS_ctr]);

       printf("\n");

       printf("Length of buffer %d\n", strlen(line));
       printf("Size of buffer CHECK %d\n", sizeof(line));               
       printf("Check line:%s\n", line);



       NUM_THREADS_ctr++;

   }

   printf("Size of buffer, len: %d\n", len);
   printf("Length of buffer %d\n", strlen(line));
   printf("Size of buffer CHECK %d\n", sizeof(line));
   printf("CHECK:%s\n", line);


   free(line); // cause the double free error
   fclose(stream);

   return 0;
}

下面是我测试过的文件:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Line 11Line 11

0 个答案:

没有答案