Home > Back-end >  Dynamic array allocation - valgrind conditional jump
Dynamic array allocation - valgrind conditional jump

Time:11-15

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));

CodePudding user response:

You never terminate the string you create in msg.

After the loop (but before you use msg as a null-terminated string with e.g. strlen(msg)) add the terminator:

msg[idx] = '\0';

There's another problem though, which might crop up unexpectedly: When you reallocate the memory you don't add space for the terminator.

Use-case for this problem: You enter a string with exactly 20 characters.

You will then have reallocated once, making the size exactly 20 bytes (characters). The last character will be put at index 19, then idx is increased to 20 (which is out of bounds). Next iteration of the loop you detect the newline, and break out, and will then set the terminator on the 21:st character in your 20-character array.

Add 1 to the size when calling realloc to solve this:

temp = realloc(msg, size   1);
  • Related