将结构传递给多个其他函数

问题描述 投票:1回答:1

我对编程比较陌生,我在将结构传递给其他函数时遇到了一些问题。这是我的实际代码:

typedef struct Memcheck {

char *memoryAdd;
char *file;
int line;

struct Memcheck_struct *next;

} Memcheck;

char *strdup2( char *str )
{
  char *new;
  new = malloc( strlen(str)+1 );
  if (new)
    strcpy( new, str );
  return new;
}

/*Allocate memory for a ptr, and add it to the top of the linked list*/
void *memcheck_malloc(size_t size, char *file, int line){

Memcheck * new_memoryCheck = NULL;
Memcheck * head = NULL;
head = malloc(sizeof(Memcheck));
new_memoryCheck = malloc(sizeof(Memcheck));


new_memoryCheck->memoryAdd = malloc(sizeof(new_memoryCheck->memoryAdd));
new_memoryCheck->file = malloc(sizeof(new_memoryCheck->file));
new_memoryCheck->file = strdup2(file);
new_memoryCheck->line = line;
new_memoryCheck->next = head;


return new_memoryCheck;
}

/*Prints the error messages*/
void printList(Memcheck *new_memoryCheck) {

Memcheck * head = NULL;
Memcheck * current = head;
head = malloc(sizeof(Memcheck));
current = malloc(sizeof(Memcheck));

printf("new_mem file: %s\n", new_memoryCheck->file);
printf("current file: %s\n", current->file);

while (current != NULL) {
    printf("in loop\n");
printf("memcheck error:  memory address %p which was allocated in file \"%s\", line %d, was never freed\n", current, current->file, current->line);
current = current->next;
}
}

int memcheck_main(Memcheck new_memoryCheck){

printf("newmem file: %s\n", new_memoryCheck.file);
printf("Entering printList\n"); 
printList(&new_memoryCheck);

return 0;
}

我有strdup2因为显然ansi没有stdrup。

我知道在某种程度上使用引用,但我不确定在哪里使用*&运算符

c struct
1个回答
1
投票

因为看起来你正在为malloc()写一个代理,它记录了哪些内存被分配到哪里,你可能需要类似的代码:

typedef struct Memcheck Memcheck;

struct Memcheck
{
    void       *data;
    size_t      size;
    const char *file;
    int         line;
    Memcheck   *next;
};

static Memcheck *memcheck_list = 0;

/* Allocate memory and record the allocation in the linked list */
void *memcheck_malloc(size_t size, const char *file, int line)
{
    Memcheck *node = malloc(sizeof(*node));
    void *data = malloc(size);
    if (node == 0 || data == 0)
    {
        free(node);
        free(data);
        return 0;
    }
    node->data = data;
    node->size = size;
    node->file = file;
    node->line = line;
    node->next = memcheck_list;
    memcheck_list = node;
    return data;
}

请注意,如果其中一个(或两个)内存分配失败,则在返回之前将释放所有内存。在null(free())指针上使用0是一个无操作。因此清理是安全的。信息可以简单地复制到结构中,如图所示;例如,只要将__FILE__传递给函数(它是一个字符串文字,因此具有与程序其余部分一样长的生命周期),就不需要为文件名额外分配内存。

© www.soinside.com 2019 - 2024. All rights reserved.