alpha9eek
alpha9eek

Reputation: 1449

union memory allocation :: stores more content than allocated memory

I have defined a union as

union person
{
    int roll;
    char fname[10];
    char lname[20];


}p1;

And the sizeof(p1)=20 bytes. but while storing the content in p1 its storing more than 20 chars.

void main()
{
    printf("\n The size of the union is %zu\t",sizeof(p1));
    printf("\n Enter the details here :\t");
    scanf("%d",&p1.roll);
    scanf("%s",p1.fname);
    scanf("%s",p1.lname);
    printf("\n The union contains are \n");
    printf("\n The roll no is :: \t %d",p1.roll);
    printf("\n The fname is :: \t %s ",p1.fname);
    printf("\n The laname is :: \t %s\n",p1.lname);


}

when i give input more than 20 char,still its stored.

Upvotes: 0

Views: 66

Answers (2)

sapi
sapi

Reputation: 10224

To add to Jonathon's answer, I would point out that the reason more than 20 chars is stored is because scanf has no idea about your union.

When you declare the union

union person
{
    int roll;
    char fname[10];
    char lname[20];

}p1;

and say

scanf("%s",p1.lname);

all scanf sees is that you have it a char * to store the string into. It doesn't see a char[20].

In other words, the additional information that you as a programmer know - that p1.lname is only 20 characters - is not visible to scanf.

Generally, in C, it's up to you as the programmer to ensure that you don't go around reading or writing more data than your buffers can handle.

Upvotes: 1

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137438

when i give input more than 20 char,still its stored.

Of course it is. Why wouldn't it? You handed scanf a pointer and basically said "write as many chars here as you possibly wish!"

scanf("%9s",p1.fname);
scanf("%19s",p1.lname);

That will prevent scanf from overrunning the buffer. Note that I've subtracted one from each length, as scanf needs to write a NUL terminator as well.

Now, the next problem: Why are you using a union? A union is used to provide different views of the same data. Writing to one member effectively trashes the contents of all others. unions are used very rarely, in constrast to structs.

If you want to store multiple related pieces of information, use a struct.

struct person
{
    int roll;
    char fname[10];
    char lname[20];
} p1;

Upvotes: 3

Related Questions