Home > Enterprise >  Inaccurate size of string while dynamic memory allocation
Inaccurate size of string while dynamic memory allocation

Time:01-08

As per the image, you can see I have inserted whole lot of text but the total length by strlen is only showing 8 (k=8).enter image description here

I wanted to print full text inserted into one string a line but it is stopping in 8th character.

`#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    
    int i;
    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    s = realloc(s, strlen(s)   1);
    int k=sizeof(strlen(s));
     for(i=0;i<sizeof(strlen(s) 1);i  )
    {
        if(*(s i)!=' ')
            printf("%c",*(s i));
        else
            printf("\n");
      fflush(stdin);
    }
    free(s);
    return 0;
}`

CodePudding user response:

  1. sizeof(strlen(s) 1) is giving you the size of the size_t type (return type of strlen function) not the length of the string
  2. i should have type size_t
  3. fflush in the input stream is not needed and is strongly implementation-defined. Read:Is this the proper way to flush the C input stream?
  4. You use realloc incorrectly. If it fails it will result in a memory leak. This realloc is not needed anyway. But you need to save the result in the temporary variable to not loose reference to the allocated memory.
char *tmp = realloc(s, strlen(s)   1);
if(tmp) s = tmp
else { /* handle error */}

CodePudding user response:

First, the sizeof operator returns the size of the type in bytes, not the number of elements in the array. To get the number of elements in s, you should use strlen(s) instead.

Second, the scanf function will stop reading input when it encounters a newline character, so if you enter a string that is longer than 8 characters, it will only read the first 8 characters. To read a string that may contain spaces, you can use fgets instead:

fgets(s, 1024, stdin);

Finally, it's not necessary to call realloc after calling scanf or fgets, because the size of s is already 1024 characters, which is more than enough to hold the input string.

With these changes, your code should work as expected. Here's the modified version:

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

int main() {
    int i;
    char *s;
    s = malloc(1024 * sizeof(char));
    fgets(s, 1024, stdin);
    int k = strlen(s);
    for(i = 0; i < k; i  ) {
        if(*(s i) != ' ') {
            printf("%c", *(s i));
        } else {
            printf("\n");
        }
    }
    free(s);
    return 0;
}
  • Related