Search code examples
cvisual-studiostructrealloc

Strange error with realloc in VS 2010


I have a code:

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

On third element of BLOC_NOTE, program crashes at

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

VS says me that OS Windows initiated a breakpoint...

Whats wrong?

Edit
Moving the code here from the comment

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

Solution

  • This is wrong:

    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 is local variable that holds the address of your first NOTE object. But when the function returns, that value is lost. You have to return the new value, since C does not have references:

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

    In C++ this would have been enough:

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