I am trying to read a line from stdin in C and at the same time dynamically allocate memory for the string using the code snippet from below. The problem is that when I run this code, calling something like strlen(msg)
results in an Conditional jump or move depends on uninitialised value(s)
in valgrinds output.
I don't understand how to get past this problem because I can't properly initialize it if I am dynamically allocating it. I've spent a really long time on this now and can't seem to figure it out... any help would be much appreciated.
char* msg = NULL;
int c;
// set initial size for dynamic allocation
msg = malloc(sizeof(char)*10+1);
int idx = 0;
char* temp = NULL;
size_t size = 10;
while (1){
c = getchar();
if(c == EOF || c == '\n'){
break;
}else if(!isalpha(c)){
free(msg);
exit(100);
}
// dynamically reallocate memory if input too large
if(size <= idx){
size += size;
temp = realloc(msg, size);
msg = temp;
}
msg[idx++] = (char)c;
}
printf("%ld", strlen(msg));