【发布时间】:2013-10-02 16:27:49
【问题描述】:
在 VS2012 (C) 中编译我的代码时收到 _CrtIsValidHeapPointer(pUserData) 消息。
我意识到我试图在指针上使用realloc,所以当我阅读其他帖子时,许多人建议使用memcpy 和const char **。我真的很喜欢这样做,但我就是不知道怎么做。
第一个代码片段:我使用的指针的 Typedef 结构 realloc
int clientcounter = 0; //Global variable since this will be needed in other functions
typedef struct client{
char name[254];
int birthday;
int landline;
int cellphone;
int clientnum;
struct client *next;
}clientdata;
我的程序读取文件的内容并通过单链表将其存储到这些变量中。
第二段代码:
void loading_file(clientdata curr[])
{
clientdata *dummy[10000] = {0};
clientdata *head;
clientdata *tail;
head = NULL;
tail = NULL;
//.... Asking for roster file
//.. memory allocation of dummy[clientcounter]
//.... Storing data to variables
if (head == NULL)
{
head = dummy[clientcounter];
}
else
{
tail->next=dummy[clientcounter];
}
tail = dummy[clientcounter];
if (head!=NULL)
{
dummy[clientcounter-1] = head;
do {
printf("\n ::%s:: Name\n",dummy[clientcounter]->name);
curr[clientcounter] = dummy[clientcounter];
dummy[clientcounter] = realloc(dummy,sizeof(item*) * clientcounter); //Error appears Here
dummy[clientcounter] = NULL;
clientcounter++;
dummy[clientcounter] = dummy[clientcounter-1]->next;
}while(dummy[totalitem] != NULL);
}
free(dummy[totalitem-1]);
}
有人告诉我,每次clientcounter++ 发生时,我都必须重新分配内存,以免泄漏。我的问题是,我知道导致错误的原因(重新分配指针),但我不知道如何解决。
谁能教我如何修复代码?
【问题讨论】:
-
您的
do{}循环无效(没有while()条件。而且我认为这段代码中的虚拟指针数组没有任何原因根本。我们也不知道clientdata或hero是什么。据我所知,您不需要该sn-p 中的任何 低级逻辑来从a 加载链表文件,你当然不需要realloc()。你想解决什么问题? -
@WhozCraig 我很抱歉。已编辑
-
@WhozCraig 所以即使
clientcounter增加,我也不需要重新分配dummy[clientcounter]?如果我删除realloc,那么我会在dummy[clientcounter] = dummy[clientcounter-1]->next;得到“访问违规读取位置” -
我的意思是,如果这一切应该做的是构建一个前向链表,那么指针数组,重新分配,所有的都不是完全需要。所以我问,你想解决什么问题。
-
@WhozCraig 我的程序在链表部分不起作用。文件中有多个“组”数据(1 组 = 5 个变量,在
typedef中声明),我的程序只打印第一组然后休息。如果我不包括realloc
标签: c pointers realloc singly-linked-list