1

我有一个代码:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

typedef struct NOTE
{
    char NAME[50],  
         TELE[30];  
    int  BDAY[3];   
} NOTE;

void AddNote(NOTE * Notes, int NotesCount, NOTE * Temp)
{
    Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));
    memcpy(Notes + NotesCount, Temp, sizeof(struct NOTE));
}

void main()
{
    int NotesCount = 0, i = 0, f = 0;
    int a;
    NOTE * BLOC_NOTE, * Temp;

    Temp = (struct NOTE *) malloc(sizeof(struct NOTE));
    BLOC_NOTE = (struct NOTE *) calloc(0, sizeof(struct NOTE));

    for(i = 0; i < 4; i++)
    {
        ShowInputDialog(Temp);
        AddNote(BLOC_NOTE, NotesCount++, Temp);     
    }
}

在 BLOC_NOTE 的第三个元素上,程序在

Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));

VS说我操作系统Windows启动了一个断点......

怎么了?

编辑
将代码从评论移到这里

void ShowInputDialog(NOTE * Temp) 
{ 
    printf("Name: "); 
    scanf("%s", (*Temp).NAME); 
    printf("Telephone: "); 
    scanf("%s", (*Temp).TELE); 
    printf("Birthday: "); 
    scanf("%d\.%d\.\%d", (*Temp).BDAY, ((*Temp).BDAY + 1), ((*Temp).BDAY + 2));
 }
4

3 回答 3

2

这是错误的:

void AddNote(NOTE * Notes, int NotesCount, NOTE * Temp)
{
    Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));
    memcpy(Notes + NotesCount, Temp, sizeof(struct NOTE));
}

Notes 是保存第一个NOTE对象地址的局部变量。但是当函数返回时,该值就丢失了。您必须返回新值,因为 C 没有引用:

NOTE* AddNote(NOTE * Notes, int NotesCount, NOTE * Temp)
{
    Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));
    memcpy(Notes + NotesCount, Temp, sizeof(struct NOTE));
    return Notes;
}

for(i = 0; i < 4; i++)
{
   ShowInputDialog(Temp);
   BLOC_NOTE = AddNote(BLOC_NOTE, NotesCount++, Temp);     
}

在 C++ 中,这已经足够了:

void AddNote(NOTE * &Notes, int NotesCount, NOTE * Temp)
{
    Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));
    memcpy(Notes + NotesCount, Temp, sizeof(struct NOTE));
}
于 2011-05-14T17:52:55.523 回答
2

好的,现在我想通了。

void AddNote(NOTE * Notes, int NotesCount, NOTE * Temp)
{
    Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));
    memcpy(Notes + NotesCount, Temp, sizeof(struct NOTE));
}

AddNote参数中NotesBLOC_NOTE. 如果 realloc 成功扩展块,那没关系。但是,如果 realloc 分配一个新块(并复制那里的所有内容),BLOC_NOTE则突然无效,因为它现在指向已释放的内存。

下次您调用 AddNode 时,内存调试器显然会检测到这一点。

于 2011-05-14T17:53:33.527 回答
0

需要检查从 malloc( )、calloc( ) 和 realloc( ) 返回的指针值。你在哪里做过这些检查?

于 2011-05-14T17:19:18.027 回答