I am trying to solve a problem and in the process I am entering the strings using getline as follows( part of my main function)
size_t n1=0,n2=0;
char *a=0, *b=0;
getline(&a,&n1,stdin);
getline(&b,&n2,stdin);
but no matter what input I give the value of n1 and n2 always stored as 120 . How can I overcome this problem to store the exact size of string I input
How can I overcome this problem to store the exact size of string I input
First, you should stop regarding this as a problem and regard it as normal behavior of getline
. You should adapt to getline
and not expect it to adapt to you.
getline
allocates a reasonable amount of spaces to work with. Allocating a smaller amount of space could require getline
to reallocate space more frequently as continuing input required larger and larger allocations. This would waste resources including energy and time.
The n1
or n2
passed to getline
by way of the second parameter is set to the size of the allocated space, not the length of the input read, and there is no way for you to alter this short of changing the implementation of getline
. getline
does not put the length of the input in n1
or n2
.
To get the length of the input that was read, save the return value of getline
:
size_t l1 = getline(&a, &n1, stdin);
size_t l2 = getline(&b, &n2, stdin);
If the allocated space is a great concern, use realloc
to inform the memory management software that the excess space is not needed:
char *temp = realloc(a, n1 = l1+1);
if (!temp) a = temp;
temp = realloc(b, n2 = l2+1);
if (!temp) b = temp;
Some realloc
implementations are likely to ignore attempts to reduce the allocated space, especially when the allocated size is small.