【问题标题】:Invalid read of size in structure结构中的大小读取无效
【发布时间】:2016-12-15 21:48:50
【问题描述】:

我和这个问题几乎相同: Getting data from pointer in struct "Invalid read/write"

但是当我尝试遵循这些建议时,我仍然遇到同样的 Invalid read of size。

我的结构是这样的

typedef struct{
   int lenght;
   int max_lenght;
   int extract;
   int inserting;
   void** structure;
} queue_t;

还有我的循环缓冲区代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#include "queue.h"

 /* creates a new queue with a given size */
queue_t* create_queue(int capacity){

    queue_t* queue = malloc (sizeof(queue_t));

    queue->lenght = 0;
    queue -> max_lenght = capacity;
    queue -> extract = 0;
    queue -> inserting = 0;
    queue -> structure = malloc(sizeof(void*) * capacity);
    return queue;
}
/* deletes the queue and all allocated memory */
void delete_queue(queue_t *queue){
    free(queue->structure);
    free(queue);
}

/*
 * inserts a reference to the element into the queue
 * returns: true on success; false otherwise
 */
bool push_to_queue(queue_t* queue, void* data){
    bool succes;
    if ((queue -> max_lenght) <= (queue -> lenght)){
        succes = false;
    }
    else{
        if (queue -> inserting == queue->max_lenght){
            queue -> inserting = 0;
        }
        queue -> structure[queue -> inserting] = data;
        queue -> inserting += 1;
        queue -> lenght += 1;
        succes = true;
    }
    return succes;
}

/*
 * gets the first element from the queue and removes it from the queue
 * returns: the first element on success; NULL otherwise
 */
void* pop_from_queue(queue_t *queue){
    void* element;
    if ((queue->lenght) <= 0){
        element = NULL;
    }
    else{
        element = queue -> structure[queue-> extract];
        queue -> extract += 1;
        queue -> lenght -= 1;
        if(queue -> extract == queue -> max_lenght){
            queue -> extract = 0;
        }
    }
    return element;
}

/*
 * gets idx-th element from the queue
 * returns: the idx-th element on success; NULL otherwise
 */
void* get_from_queue(queue_t *queue, int idx){
    void* element;
    if(idx >= queue -> lenght){
        element = NULL;
    }
    else{
        if (queue -> extract + idx >= queue->max_lenght){
            element = &queue -> structure[queue->extract+idx - queue->         max_lenght];
        }
        else{
            element = &queue -> structure[queue-> extract+idx];
        }
    }
    return element;
}

/* gets number of stored elements */
int get_queue_size(queue_t *q){
    return q -> lenght;
}

当我尝试调用 pop_from_queue 时,我仍然收到来自 valgring 的消息,表明我在数组之外。 例如:

==236== Invalid read of size 4
==236==    at 0x4009C8: pop_from_queue (queue.c:53)
==236==    by 0x400721: pop (main.c:33)
==236==    by 0x400817: main (main.c:78)
==236==  Address 0x51fc040 is 0 bytes inside a block of size 24 free'd
==236==    at 0x4C2BD57: free (vg_replace_malloc.c:530)
==236==    by 0x40073D: pop (main.c:35)
==236==    by 0x400817: main (main.c:78)
==236==  Block was alloc'd at
==236==    at 0x4C2AC3D: malloc (vg_replace_malloc.c:299)
==236==    by 0x4008B8: create_queue (queue.c:10)
==236==    by 0x400798: main (main.c:57)
==236==
==236== Invalid read of size 8
==236==    at 0x4009DC: pop_from_queue (queue.c:57)
==236==    by 0x400721: pop (main.c:33)
==236==    by 0x400817: main (main.c:78)
==236==  Address 0x51fc050 is 16 bytes inside a block of size 24 free'd
==236==    at 0x4C2BD57: free (vg_replace_malloc.c:530)
==236==    by 0x40073D: pop (main.c:35)
==236==    by 0x400817: main (main.c:78)
==236==  Block was alloc'd at
==236==    at 0x4C2AC3D: malloc (vg_replace_malloc.c:299)
==236==    by 0x4008B8: create_queue (queue.c:10)
==236==    by 0x400798: main (main.c:57)
==236==
==236== Invalid read of size 4
==236==    at 0x4009E4: pop_from_queue (queue.c:57)
==236==    by 0x400721: pop (main.c:33)
==236==    by 0x400817: main (main.c:78)
==236==  Address 0x51fc048 is 8 bytes inside a block of size 24 free'd
==236==    at 0x4C2BD57: free (vg_replace_malloc.c:530)
==236==    by 0x40073D: pop (main.c:35)
==236==    by 0x400817: main (main.c:78)
==236==  Block was alloc'd at
==236==    at 0x4C2AC3D: malloc (vg_replace_malloc.c:299)
==236==    by 0x4008B8: create_queue (queue.c:10)
==236==    by 0x400798: main (main.c:57)
==236==
==236== Invalid read of size 4
==236==    at 0x4009FB: pop_from_queue (queue.c:58)
==236==    by 0x400721: pop (main.c:33)
==236==    by 0x400817: main (main.c:78)
==236==  Address 0x51fc048 is 8 bytes inside a block of size 24 free'd
==236==    at 0x4C2BD57: free (vg_replace_malloc.c:530)
==236==    by 0x40073D: pop (main.c:35)
==236==    by 0x400817: main (main.c:78)
==236==  Block was alloc'd at
==236==    at 0x4C2AC3D: malloc (vg_replace_malloc.c:299)
==236==    by 0x4008B8: create_queue (queue.c:10)
==236==    by 0x400798: main (main.c:57)
==236==
etc.

我是结构的初学者,所以我欢迎任何帮助。

编辑: 这些错误在线:

53 if ((queue->lenght) <= 0){
57 element = queue -> structure[queue-> extract];
58 queue -> extract += 1;
59 queue -> lenght -= 1;
60 if(queue -> extract == queue -> max_lenght){
89 return q -> lenght;

我的主要程序方法:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

#include "queue.h"


/* allocate new integer with value a and add it to the queue */
void add(int a, queue_t *queue)
{
   int *p = (int*)malloc(sizeof(int));
   *p = a;
   bool ret = push_to_queue(queue, (void*)p);
   if (!ret) {
      // free memory on failure
      free(p);
   }
}

/* print the int value on pointer p */
void print_int(void *p)
{
   if(p != NULL){
      printf("%d\n", *((int*)p));
   } else {
      printf("NULL\n");
   }
}

/* pop from the queue, print and free the element */
void pop(queue_t *queue)
{
   void *p = pop_from_queue(queue);
   print_int(p);
   free(queue);
}

/* get i-th element and print it (do not remove them) */
void get(int idx, queue_t *queue)
{
   print_int(get_from_queue(queue, idx));
}

/* 
 * TEST PROGRAM
 * - reads commands from stdin and executes them in the queue
 */
int main(int argc, char *argv[])
{
   int n;
   /* the tested queue */
   queue_t *queue;

   // read the size of the queue
   scanf("%d", &n);
   // create queue
   queue = create_queue(n);

   while (true) {
      char s[2];
      // read one command
      int ret = scanf("%1s", s);
      if (ret != 1) {
     break;
      }

      // add command
      if (s[0] == 'a') {
     int a;
     // read the argument of the command
     ret = scanf("%d", &a);
     if (ret != 1) {
        break;
     }
     add(a, queue);
     // remove command   
      } else if (s[0] == 'r') {
     pop(queue);
     // get command  
      } else if (s[0] == 'g') {
     int a;
     // read the argument of the command
     ret = scanf("%d", &a);
     if (ret != 1) {
        break;
     }
     get(a, queue);
      }
   }

   // remove rest of the elements in the queue
   while (get_queue_size(queue)) {
      void *p = pop_from_queue(queue);
      free(p);
   }

   // free memory
   delete_queue(queue);
   queue = NULL;

   // return 0 on succes
   return 0;
}

【问题讨论】:

  • 您对什么是指向指针的指针有一些误解。您的代码在多个地方都是错误的。你在哪里分配子数组?指针不是数组。关于您的文字:我们不是调试服务,您的**具体**问题是什么?调试器说什么?请参阅How to Ask 并提供minimal reproducible example
  • 能否提供主要功能代码?
  • @NicolasDefranoux: main 不是方法,在 C 和 C++ 中都不是。而C根本不支持方法
  • 在 get_from_queue 中,我认为你在两行 element = &queue 上有一个额外的 &。
  • pop free(queue); --> free(p);

标签: c struct valgrind


【解决方案1】:

通过肉眼查看代码,我发现了一些直接的问题。

/* pop from the queue, print and free the element */
void pop(queue_t *queue)
{
    void *p = pop_from_queue(queue);
    print_int(p);
    free(queue);
}

我认为您的意思不是在这里释放整个 queue,而是释放 p


void delete_queue(queue_t *queue){
    free(queue->structure);
    free(queue);
}

由于queue-&gt;structure 是一个指针列表,这只会为列表释放内存。它指向的内存仍然需要释放。这可以是调用者的责任,但也可以卸载到队列中。

对于这样的通用结构,您通常会为该结构提供一个函数指针,该指针知道如何释放队列中的内存。举个很好的例子,看看the initializer of GLib's pointer arrays take a destroy function


bool push_to_queue(queue_t* queue, void* data){
    bool succes;
    if ((queue -> max_lenght) <= (queue -> lenght)){
        succes = false;
    }
    else{
        if (queue -> inserting == queue->max_lenght){
            queue -> inserting = 0;
        }
        queue -> structure[queue -> inserting] = data;
        queue -> inserting += 1;
        queue -> lenght += 1;
        succes = true;
    }
    return succes;
}

if ((queue -&gt; max_lenght) &lt;= (queue -&gt; lenght)) 包含一个无效状态,其中queue -&gt; max_lenght 小于 queue-&gt;lenght。那不应该发生。

最好使用assert 明确检查所有内容是否有效。这是一个调试语句,它断言必须为真的东西,如assert( queue-&gt;length &lt;= queue-&gt;max_length )。如果不是,程序将崩溃并通知您断言失败。否则,您的代码将尝试插入太多元素并且已经有太多相同的元素。

push_to_queue 的开头使用该断言,您可以检查if( queue-&gt;max_length == queue-&gt;length )


我建议您先对队列库进行单元测试,然后再尝试在更大的程序中使用它。用正常和边缘情况测试每种方法。比如……

void test_delete_queue() {
    queue_t *q = create_queue(3);

    int nums[3] = {4,5,6};
    for( int i = 0; i < 3; i++ ) {
        push_to_queue(q, &num);
    }

    delete_queue(q);
}

虽然这似乎不包含任何测试,但它让您知道 delete_queue 没有段错误,并且使用 valgrind 运行它会检测到任何泄漏。

再举一个例子,在阅读您的代码时,我对queue-&gt;insertingqueue-&gt;extracting 高度怀疑。在我看来,如果你推得够多,它们就会失去同步。所以我测试了它。而且,令我惊讶的是,它有效!现在我们确定这不是问题。

void test_push_pop() {
    queue_t *q = create_queue(3);

    int nums[4] = {10, 20, 30, 40};

    /* Push twice then pop once */
    assert( push_to_queue(q, &nums[0]) );
    assert( push_to_queue(q, &nums[1]) );
    assert( (int*)pop_from_queue(q) == &nums[0] );

    /* Push and pop again */
    assert( push_to_queue(q, &nums[2]) );
    assert( (int*)pop_from_queue(q) == &nums[1] );

    /* Push one more than the max length. This should be ok
       as we've already popped twice */
    assert( push_to_queue(q, &nums[3] ) );
    assert( (int*)pop_from_queue(q) == &nums[2] );
    assert( (int*)pop_from_queue(q) == &nums[3] );

    assert( get_queue_size(q) == 0 );

    delete_queue(q);
}

但是对pop 进行类似的测试是行不通的,因为它会释放整个队列。

【讨论】:

  • 这个答案的第一点很好,但其他点恐怕是错误的。在 delete_queue 上,队列不拥有数据,因此释放其内容是不合法的,处理元素分配/释放是调用者的责任。在 push_to_queue 和 assert 上,队列已满的情况是队列拒绝插入数据的有效条件,不需要断言。
  • 添加单元测试很好,但请测试一些东西,不要依赖 valgrind 来检查内存问题。并且提供的代码不会删除分配的项目:( 最后,push 和 pop 方法是理智的,如果你 push 太多 push 返回 false,如果你 pop 太多 pop 返回 NULL,因为它们都检查长度。
  • @NicolasDefranoux 我推荐了assert,因为代码检查了if( queue -&gt;max_lenght &lt;= queue-&gt;lenght ),但max_lenght绝不应该小于 lenght,这表明出了问题.至于释放,你可能是对的,这应该取决于调用者,我会解决这个问题。至于test_delete_queue,不知道你是怎么直接测试内存已经被释放了,所以没有asserts;没关系。它正在测试删除不会出现段错误或其他东西。 push/pop 确实是理智的,现在我知道它们是因为我测试了它们。 :)
猜你喜欢
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 2012-07-21
  • 2014-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多