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

时间:2018-03-05 04:56:54

标签: c struct

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

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。

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

1 个答案:

答案 0 :(得分: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;
}

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