cheshire
cheshire

Reputation: 1159

Correct use of malloc and strcat to avoid memory errors with valgrind

I have stored vertices in my tempStorage :

typedef struct {
    int pred[8];
    int succ[8];
} arc_set;

arc_set tempStorage;

for example .pred are 0,1,1,2,2 and .succ are 2,2,3,3,1

I have made a char *links = malloc(sizeof(char) * 100); to store these numbers and print them like this:

            char *temp = malloc(10);

            for (int l = 0; l < 8; l++){

                    sprintf(temp, "%d-%d ", tempStorage.pred[l], tempStorage.succ[l]);
                    strcat(links, temp);

            }
            free(temp);

            fprintf(stdout, "Solution %d edges: %s",countLinks, links);
            fprintf(stdout, "\n");

storing strings in format "%d-%d " in temp with sprintf and then with strcat concat that with links.

it does print everything correctly but when I test it with valgrind --leak-check=full --track-origins=yes -v ./programname I do get:

Conditional jump or move depends on uninitialised value(s)
==12322==    at 0x4C2C66A: strcat (vg_replace_strmem.c:307)
==12322==    by 0x4013CC: main (program.c:251)
==12322==  Uninitialised value was created by a heap allocation
==12322==    at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==12322==    by 0x401270: main (program.c:225)

where c:251 is strcat(links, temp); and c:225 is my char *links = malloc(sizeof(char) * 100);

am I using strcat wrong or what is the problem here?

Upvotes: 0

Views: 234

Answers (1)

aragaer
aragaer

Reputation: 17848

Memory you've got from malloc isn't zero-initialized by default. And strcat will append the new to the end of the string. For non-zero-initialized chunk of memory that could be just anywhere.

You don't need to set the whole links to zero -- just first byte would be enough. Still memset(links, 0, 100); right after malloc would not hurt.

Upvotes: 1

Related Questions