Click here to Skip to main content
15,920,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
There are two strings in this code one is an array and another one is dynamically created using pointer.

1.If my input is less than 50 for string1 and less than 10 for string2 will the space that is not filled get wasted ,if so how to reduce the size.
2.In case of string 2 malloc size parameter is 10 and fgets size parameters is 10 what will happen if i increase the size to fgets(string2,50,stdin) which is greater than malloc size?
3.how to calculate the final size of input string in each case?I have used sizeof operator but it gave the hardcoded size that is 50 and 10 respectively for string1 and string2
4.Is there any other better approach to create a dynamic string?

What I have tried:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int size=10;
    char string1[50];       
    char *string2;
    string2=(char *)malloc(size*sizeof(char));

    fgets(string1,10,stdin);
    printf("%s",string1);

    fgets(string2,10,stdin);
    printf("%s",string2);

}
Posted
Updated 6-Aug-16 23:20pm
v2

1) yes, it will be wasted -- although wasting a few bytes is no major problem on today's computers.

2) If you specify a greater length in the fgets call than is available in your buffer the outcome is undefined. The operation will overwrite some memory behind your allocated buffer, the outcome of which is undefined. In the worst case it can result in a program crash.

3) To determine the effective length of a null-terminated string use the function strlen, or its cousins for wide-characters.

4) Yes, there is a better approach, but it requires C++. There you have pre-built classes like std::string or CString that do most of the hard work of buffer management for you.
 
Share this answer
 
Quote:
What will be happen to the size of string in this code?
Nothing, what you store in a variable do not change its size.
1) Yes, it waste space, not a big problem.
2) C/C++ are unchecked, so you are responsible of taking care of this.
This lead to a problem called buffer overflow Buffer overflow - Wikipedia, the free encyclopedia[^]
The problem is avoided if you use managed languages.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900