VoidWhisperer
VoidWhisperer

Reputation: 95

c - Valgrind - "Invalid write of size 1"

I'm completely lost on this, despite now trying to look for a solution for about two hours:

Valgrind is spitting out a bunch of invalid read of size 1 and invalid write of size 1 with this code, and I can't figure out how to fix it.

char *movieGetDirector(const movie *m)
{
 char *tmp = NULL ;
 tmp = malloc(strlen(m->director)+1) ;
 strcpy(tmp, m->director) ;
 return tmp ;
}

It's getting an invalid read of size 1 on the line with strlen and then an invalid write on the strcpy line. I know that m->director is definitely a string, since testing it with gdb does reveal that it is a string and it has text. All of the solutions on google for this error relate to not having that +1 there, but I have it there and it's still an issue. How can I fix this?

Upvotes: 1

Views: 2541

Answers (1)

Mike Frysinger
Mike Frysinger

Reputation: 3062

your malloc/strlen/strcpy calls look fine. most likely the code that is setting up m and m's director field are doing it wrong and the memory is corrupted. you should double check where that variable is allocated & initialized.

that said, your function seems to be duplicating the existing strdup function. so you probably want to write:

char *movieGetDirector(const movie *m)
{
    return strdup(m->director);
}

Upvotes: 2

Related Questions