I'm a complete novice to programming and I really need your help. After calling AddS more than once, and then calling ListS to display everything stored in struct subject *a, the first print of the struct member tag is printed only up to 12 characters correct, followed by random trailing characters. On the next iteration of the loop, tag is printed with all characters correct. I've tried lowering the size of tag and it seems that it removed the trailing characters. What exactly is happening here?
struct store
{
char call[7], tag[450];
int units;
};
void AddS(struct store *a, int *n)
{
char ecode[8], etags[450];
int f, error = 0;
struct store *tempptr;
scanf("%s", ecode);
scanf("%d", &f);
scanf("%s", etags);
NameLimit(ecode);
if(Initial(ecode) && Occurrence(ecode, a, *n))
{
printf("Error.\n");
error++;
}
if(!error)
{
if(*n)
{
tempptr = realloc(a, *n + 1);
a = tempptr;
}
if(tempptr || !*n)
{
strcpy((a + *subctr) -> call, ecode);
(a + *n) -> units = f;
if (etags[0] == '.')
(a + *n) -> tag[0] = '\0';
else
strcpy((a + *n) -> tag, etags);
printf("%s added.\n", ecode);
*n = *n + 1;
}
else if(tempptr == NULL)
{
printf("No space.\n");
exit(1);
}
}
}
void ListS(struct store *a, int n)
{
int i, j;
for(i = 0; i < n; i++)
printf("%s %d %s\n", (a + i) -> call, (a + i) -> units, (a + i) -> tag);
}
The second argument to realloc() is a byte size for the new allocation.
There's not enough code shown to be sure, but this:
tempptr = realloc(a, *subctr + 1);
should very probably be
tempptr = realloc(a, (*subctr + 1) * sizeof *a);
The member char code[7] defined in the structure struct subject is less than char ecode[8] that you have defined inside your AddS() function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With