I have a program which takes as input a Name and if the input is less then the allowed size it will be saved in a Pointer.
If the input is bigger then allowed size then the realloc
function will be used to satisfy the memory needed.
The program at this point allocates only 6 bytes, 5 for name MICHI
and 1 for '\0'.
If the user types MICHAEL
then the program allocates enough memory for that pointer to fit MICHAEL
inside that pointer.
Here is the Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person{
char *name;
}pers;
void addMem(void){
unsigned int length = 6;
size_t newLength = 0;
unsigned int newSize = 0;
unsigned int i =0;
char *name;
int c;
name = malloc(lenght);
if(name == NULL){
exit(1);
}
newSize = length;
printf("Enter your name:> ");
while ((c = getchar()) != '\n' && c!=EOF){
name[i++]=(char)c;
if(i == newSize){
newSize = i+length;
name = realloc(name, newSize);
}
}
name[i] = '\0';
newLength = strlen(name)+1;
pers.name = malloc(newLength);
memcpy(pers.name, name, newLength);
free(name);
name = NULL;
}
int main(void){
addMem();
printf("Your name is:> %s\n",pers.name);
free(pers.name);
pers.name = NULL;
return 0;
}
The Program works fine, but I need to make it somehow that realloc() will give only a maximum size of memory, because at this point it will realloc until User pres ENTER.
This means that i have 6 byte for Michi (5 + 1 for '\0') and the maximum size should be 8 (7 for Michael and 1 for '\0').
How can I do that?
EDIT:
I hope you understand now.
My program accept only names with 5 letters. At some point I decided that may program should accept names with max 10 Letters. I allocated already memory for 5 (michi). If you type Michael we have 7 letters so the program should allocate another two for Michael. But if i type Schwarzernegger, well this name is too long i do not accept it so i need to make my program to allocate memory only for michael.
As Enzo's answer to stop after 7 letter you can use.
while ((c = getchar()) != '\n' && c != EOF) {
name[i++] = (char) c;
if (i >= length) {
if(i+1<=7)
name = realloc(name, i + 1);
else
{
//generate error message
}
}
}