结构中的大小读取无效

-2 c struct valgrind

我有与这个几乎相同的问题: 从结构“无效读/写”中的指针获取数据

但是当我尝试遵循这些建议时,我仍然对大小进行了相同的无效读取。

我的结构是这样的

typedef struct{
   int lenght;
   int max_lenght;
   int extract;
   int inserting;
   void** structure;
} queue_t;
Run Code Online (Sandbox Code Playgroud)

我的循环缓冲区代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试调用 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.
Run Code Online (Sandbox Code Playgroud)

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

编辑: 这些错误在线上:

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;
Run Code Online (Sandbox Code Playgroud)

我的主要程序方法:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Sch*_*ern 5

通过眼睛浏览代码,我看到了一些直接的问题。

/* 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);
}
Run Code Online (Sandbox Code Playgroud)

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


void delete_queue(queue_t *queue){
    free(queue->structure);
    free(queue);
}
Run Code Online (Sandbox Code Playgroud)

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

对于像这样的通用结构,您通常会为该结构提供一个函数指针,该指针知道如何释放队列中的内存。举个很好的例子,看看GLib 的指针数组的初始化器是如何使用 destroy 函数的


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;
}
Run Code Online (Sandbox Code Playgroud)

if ((queue -> max_lenght) <= (queue -> lenght))是包括其中无效状态queue -> max_lenght小于 queue->lenght。那不应该发生。

最好使用assert. 这是一个调试语句,它断言某些东西必须为真,例如assert( queue->length <= queue->max_length ). 如果不是,程序将崩溃并通知您断言失败。否则,您的代码将尝试插入一个过多的元素并且已经有太多相同的元素。

在开始时设置该断言后,push_to_queue您可以检查if( queue->max_length == queue->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);
}
Run Code Online (Sandbox Code Playgroud)

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

再举一个例子,在阅读你的代码时,我非常怀疑queue->insertingqueue->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);
}
Run Code Online (Sandbox Code Playgroud)

但是类似的测试pop不起作用,因为它会释放整个队列。