VS 2010中realloc的奇怪错误

时间:2011-05-14 17:05:50

标签: c visual-studio struct realloc

我有一个代码:

#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告诉我OS OS启动了一个断点......

怎么了?

修改
从评论中移动代码

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));
 }

3 个答案:

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

答案 1 :(得分: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时,内存调试器显然会检测到。

答案 2 :(得分:0)

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