I have to read a string from stdin, allocating memory dinamically without wasting it. I've done this, but i'm not convinced about it,because in this way i think i waste memory!
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *alloc_memory(int n)
{
char *p;
p=malloc(n*sizeof(char));
if(p==NULL)
{
fprintf(stderr,"Error in malloc\n");
exit(EXIT_FAILURE);
}
return p;
}
int main(int argc, char *argv[])
{
if(argc != 1)
{
fprintf(stderr,"Usage: %s \n",argv[0]);
return EXIT_FAILURE;
}
char string[64];
int lung;
char *p,*s,*w;
printf("Insert string: \n");
p=fgets(string,63,stdin);
if(p==NULL)
{
fprintf(stderr,"Error in fgets\n");
exit(EXIT_FAILURE);
}
printf("You've inserted: %s", string);
lung=strlen(p);
s = alloc_memory(lung+1);
w=strncpy(s,p,lung);
printf("Final string:%s", w);
return EXIT_SUCCESS;
}
any idea? Should i read one character at a time?
strncpy().