我是否在我在c中实现的添加功能中正确实例化指针



我不确定为什么我的添加功能会导致许多内存泄漏,无效的读取和无效的写入。当然,它在其中包含其他几个功能,因此我也包括它们。我讨厌上传很多代码,但是我不确定这里的问题在哪里。

heap.h头文件:

struct Entry {
  int key;
  char* value;
};
typedef struct Entry Entry;
struct Heap {
  int capacity;
  int size;
  Entry** elements;
};
typedef struct Heap Heap;

heap.c:

void add(Heap* h, int priority, char* val) {
  if (h->size >= h->capacity) {
    expandCapacity(h);
  }
  //insert at end of storage array and bubble up
  Entry* toAdd = calloc(1, sizeof(Entry*));
  toAdd->key = priority;
  toAdd->value = calloc(1, sizeof(char*));
  toAdd->value = val;
  h->elements[h->size]=toAdd;
  h->size += 1;
  bubbleUp(h, h->size);
}

泡沫和互换具有功能,我要做的就是为此项目调整它们并将其转换为C,因此,尽管从逻辑上讲它们对我来说是有意义的,但这样做可能存在问题。

void bubbleUp(Heap* h, int index) {
   if(index <= 0) { return; }
   Entry* e = h->elements[index];
   Entry* parent = h->elements[(index-1)/2];
   int comp = strcmp(e->value, parent->value);
   if(comp > 0) {
     swap(h, index, parent->key);
     bubbleUp(h, parent->key);
   }
   else {
     return;
   }
}
void swap(Heap* h, int index1, int index2) {
   Entry* tmp = h->elements[index1];
   h->elements[index1] = h->elements[index2];
   h->elements[index2] = tmp;
}

in

void add(Heap* h, int priority, char* val) {
    if (h->size >= h->capacity) {
        expandCapacity(h);
    }
    //insert at end of storage array and bubble up
    Entry* toAdd = calloc(1, sizeof(Entry*));
    toAdd->key = priority;
    toAdd->value = calloc(1, sizeof(char*));
    toAdd->value = val;
    h->elements[h->size]=toAdd;
    h->size += 1;
    bubbleUp(h, h->size);
}

您想为一个结构条目分配内存,而不是为其指针,所以这将完成工作

Entry* toAdd = calloc(1, sizeof(Entry));

您不需要为指针toAdd->value分配内存,因为它已经是由编译器分配的 stat上

此时,如果要复制指针,只需删除此行toAdd->value = calloc(1, sizeof(char*));相反,如果要复制字符串的内容,则必须使用strncpy

这是内存泄漏。分配一个块,然后立即丢失。我只会删除第一行。

toAdd->value = calloc(1, sizeof(char*));
toAdd->value = val;

另外,您应该在此处分配sizeof(Entry),而不是指针的大小。

Entry* toAdd = calloc(1, sizeof(Entry*));

最新更新