gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:23 25 4
gpt4 key购买 nike

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

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。

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

最佳答案

由于您似乎正在为 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;
}

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

关于c - 将结构传递给多个其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49103702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com