0
#include<stdio.h>

struct classifier
{
    char src_address[15];
    char dst_address[15];
    int src_port;
    int  dst_port;
};

main()
{
    int i;
    struct classifier clsf[4];
    struct classifier *ptr;

    for(i = 0; i < 2; i++)
    {
        ptr = & clsf[i];
        scanf("%s",ptr[i].src_address);
        scanf("%s",ptr[i].dst_address);
        scanf("%d",&ptr[i].src_port);
        scanf("%d",&ptr[i].dst_port);
        display(ptr[i]);
    }
}

void display(struct classifier ptr)
{
    printf("\n%s", ptr.src_address );
    printf("\n%s", ptr.dst_address );
    printf("\n%d", ptr.src_port);
    printf("\n%d", ptr.dst_port );
}

the o/p that i get is like this

this is i/p

123.123.123.123 
213.234.234.124
3244
1342

o/p
123.123.123.123213.234.234.124
213.234.234.124
3244
1342 

why is that first value repeating. what is wrong in the code

hunter
  • 62,308
  • 19
  • 113
  • 113
pradeep
  • 75
  • 1
  • 2
  • 9

1 Answers1

6

Because you write too much data into your strings.

char src_address[15];

is 15 chars long, including the terminating 0 character, thus you must not put more than 14 characters into it. However, 123.123.123.123 is 15 chars.

Since the two fields src_address and dst_address happen to be stored in consecutive memory blocks, the value written into the latter follows immediately - without a separating 0 byte - the former. Thus printf cannot but print both when you intend to print the former.

You should reserve enough space in your char arrays to incorporate the terminating 0 value (and explicitly ensure that it really is put there!). In general, in real life apps you should defend yourself against buffer overruns caused by too long input.

Community
  • 1
  • 1
Péter Török
  • 114,404
  • 31
  • 268
  • 329