Hi all,
I'm new to this board. I've had some forgotten experience with C, but now I'm refreshing.
I've always viewed string input in C as a great limitation on my programmes, because you have to know the lenght of the string beforehand, so I thought why not write a function that will take care of the memory allocation for me? Here's the code I wrote for the function strin, I also wrote a complete programme (with main()) just to test it.
Like I said, I'm refreshing my knowledge of C and for things like the declaration of p[] in strin() I switched between many forms likeCode:#include <stdio.h> #include <string.h> #include <stdlib.h> char* strin(FILE* stream); int main (void) { /* variable declaration */ char* p; /* Input */ printf("\nEnter a line of text: "); if((p = strin(stdin)) == NULL) { fprintf(stderr, "\nstrin:String Input Failure.\n\n"); exit(1); } puts(p); return 0; } char* strin(FILE *stream) { char p[1]; char *t; int ch; int ind = 0; while((ch = fgetc(stream)) != '\n') { if((t = realloc(p, sizeof(char) + strlen(p))) == NULL) return NULL; p[ind++] = (char)ch; } p[strlen(p)] == '\0'; return p; }
char *p
char p[]="";
etc.
I know that even without the segfault there's a lot wrong with the programme, but for now I just want to get it running even if it doesn't do what I intend it to do. I'll take care of other problems later.
My understanding is that because p is a name of a string in strin(), then it is a pointer as well However, based on what I understand from GDB, the segfault occurs onAny help in solving this seg fault would be appreciate.Code:p[ind++] = (char)ch;