Search code examples
clinuxmallocvalgrindmemcpy

C memalloc & mempy give conditional jump valgrind error while splitting a char array


I am trying to split this char array into two parts first 4 character is one part rest is second part Its working but I get conditional jump issue on valgrind can any one advice the solution to this please

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    const char src[50] = "FLSZGRGR";
    char *dest1 = malloc(5 * sizeof(char));
    memcpy(dest1, src, 4);
    printf("%s \n", dest1);
    if (strcmp(dest1, "FLSZ") == 0)
        printf("EQUAL 1 \n");

    char *dest2 = malloc(5 * sizeof(char));
    memcpy(dest2, src + 4, 4);
    printf("%s \n", dest2);
    if (strcmp(dest2, "GRGR") == 0)
        printf("EQUAL 2 \n");

    free(dest1);
    free(dest2);
    return (0);
}

Solution

  • The problems likely arise because your dest1 and dest2 strings are not explicitily NUL-terminated: the calls to printf (using the %s format) and strcmp require that the strings be NUL-terminated.

    To fix this, you can either explicitly set the last char element to the NUL character:

    memcpy(dest1, src, 4);
    dest1[4] = '\0'; // Explicitly set NUL terminator (do the same for "dest2")
    

    or use calloc in place of malloc (which will set all elements to zero):

    char *dest1 = calloc(5, sizeof(char)); // And similarly for "dest2"
    

    Without either of these, the memory allocated by the malloc calls will be uninitialzed, and you are entering the territory of undefined behaviour! The last elements of the dest1 and dest2 strings may be zero (which would make your code seem to work) but they may not be - in which case the printf and strcmp calls will keep looking, beyond the end of the allocated memory buffers, for the 'signal' NUL terminator.