Search code examples
cstringdynamic-memory-allocation

I want to store a character string in block of memory space created by malloc and then modify the same space to store a much larger string


Here is the code

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

int
main()
{ 

int n,i;

printf("Enter the size or the number of chracters that you want to enter inside the string.\n");
scanf("%d",&n);

char *p = (char*)malloc((n+1)*sizeof(char));
if(p==NULL)
 {
 printf("Memory allocation fails..");
 exit(0);
 }
 
puts("Enter string");
for(i=0;i<(n+1);i++)
scanf("%c",p+i);

*(p+i)= '\0';

printf("String entered %s",p);

fflush(stdin);

printf("\nEnter new size\n");
scanf(" %d",&n); 

p = realloc(p,(n+1)*sizeof(char));

puts("Enter new string");
scanf("%d", &n);

 for(i=0;i<(n+1);i++)
 scanf("%c",p+i);
 
 *(p+i)= '\0'; 
 
 printf("New string \n%s",p);
 
 free(p);
 
return 0;
}

I used an online compiler (https://www.onlinegdb.com/online_c_compiler).

The question that I want to ask. When I enter more elements than the size that I initialized for the string during runtime. It does not take the next input and prints the result. And when I enter less than the size limit, it does not go to the next part. Instead, it takes multiple inputs to move towards the next part and print the results.

When I enter string within the size limit.

enter image description here

When I enter string more than the size limit.

enter image description here

When I try to enter string less than the size limit. enter image description here

Can anybody please tell me what I am doing wrong?


Solution

  • The loop

    for(i=0;i<(n+1);i++)
        scanf("%c",p+i);
    

    will keep running until you've entered all characters. That's why you need to write a until the array is filled in the last screenshot. If you want the line to be read when enter is pressed you can use fgets

    Regarding the other screenshots, as per C standard, it is undefined behavior to use fflush(stdin). Thats why the input buffer doesn't get flushed. You can use

    int c;
    while((c = getchar()) != '\n' && c != EOF); //Discard
    

    to flush stdin