I am currently looking into memory allocation in C. The code below should read characters from standard input one by one and write them to string s. First I allocate memory for s using malloc. Initial size: CHUNK_SIZE. The counter variable counts the number of letters entered. After it becomes larger than the current size l of string s, the code should reallocate string s with the new size l CHUNK_SIZE.
#include <stdio.h>
#include <stdlib.h>
#define CHUNK_SIZE 10
int main(void)
{
int l = CHUNK_SIZE;
// s - is the string where to write letters from stdin
char *s = (char *)malloc(l * sizeof(char));
char *p = s;
// counter for counting entered letters
int counter = 0;
while ((*p = getchar()) != '\n') {
counter ;
// reallocate memory if amount of entered letters more than size of s
if (counter > l - 1) {
l = CHUNK_SIZE;
s = (char *)realloc(s, l * sizeof(char));
}
}
*p = '\0';
printf("%s", s);
return 0;
}
The problem is that it seems that the memory space is being successfully reallocated. But the program does not write the letter to the string after the second reallocation. With CHUNK_SIZE set to 10, only 20 letters are stored.
Entered: This is a string and I like it
Saved to string: This is a string and
CodePudding user response:
Based on answers provided by Ian Abbott and Paul Lynch this code is working correctly now:
#include <stdio.h>
#include <stdlib.h>
#define CHUNK_SIZE 10
int main(void)
{
int l = CHUNK_SIZE;
char *s = (char *)malloc(l * sizeof(char));
int counter = 0;
while ((s[counter] = getchar()) != '\n') {
counter ;
if (counter > l - 1) {
l = CHUNK_SIZE;
s = (char *)realloc(s, l * sizeof(char));
}
}
s[counter] = '\0';
printf("%s\n", s);
return 0;
}
CodePudding user response:
As suggested in comments, p should be updated after realloc
, for example :
if (counter > l - 1) {
l = CHUNK_SIZE;
s = (char *)realloc(s, l * sizeof(char));
p = s l - CHUNK_SIZE; // just after the last input char
}
Also you should probably check the return value of malloc
and realloc
.