Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic array allocation – valgrind conditional jump

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading