Search code examples
cpointersmemory-leaksvalgrinddynamic-memory-allocation

Understanding results with valgrind


For the following code I have the following defintion:

typedef struct string {char* data; int length;} string;

If I run the following code with valgrind, I got conditional jump or move depends on unitinialized value and seg. fault:

string* s = (string*) malloc(sizeof(string));
strcpy("Hello", s->data);
free(s);

First of all, I can't understand why I got above errors. I thought if I add to that code free(s->data) it will freed memory but program will run ok.

How I think: I know sizeof(string) equal to 4(pointer to char) + 4(int) = 8. then we allocate 8 bits for s. strcpy will copy the string into data but I got a problem here. why?


Solution

  • There are multiple problems:

    string* s = (string*) malloc(sizeof(string));
    

    which should better be

    string* s = malloc(sizeof(*s));
    

    allocates memory for s->data, but does not make s->data point to any valid memory location. If you want to make use of the memory location, you need to make sure that it points to a valid memory location. For example: you'd need to malloc() for s->data seperately.

    That said, the syntax for strcpy() says, it's strcpy(dest, source), so in your case

    strcpy("Hello", s->data);
    

    attempts to

    • read from an unitilized memory location
    • write into a string literal

    either of which invokes undefined behaviour.

    You should write

    strcpy(s->data, "Hello");
    

    after ensuring s->data is a valid destination.