Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valgrind Invalid read size of 1

Tags:

c

valgrind

For the life of me i cant work out why I am getting an invalid read size of 1 for this code snippet, I'm pretty sure its got something to do with me abusing the char *url pointer...

char *extractURL(char request[])
{
char *space = malloc(sizeof(char *));
space = strchr(request, ' ')+1;
char *hostend = malloc(sizeof(char *));
hostend = strchr(request, '\r');
int length = hostend - space;
if (length > 0)
{
    printf("Mallocing %d bytes for url\n.", length+1);
    char *url = (char *)malloc((length+1)*sizeof(char));
    url = '\0';
    strncat(url, space, length);
    return url;
}
//else we have hit an error so return NULL
return NULL;    
}

The valgrind error I am getting is :

==4156== Invalid read of size 1

==4156==    at 0x4007518: strncat (mc_replace_strmem.c:206)

==4156==    by 0x8048D25: extractURL ()

==4156==    by 0x8048E59: processRequest ()

==4156==    by 0x8049881: main ()

==4156==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

Can someone 'point' me in the right direction?

like image 586
DMcB1888 Avatar asked Feb 24 '12 02:02

DMcB1888


People also ask

What does invalid read of size mean in Valgrind?

An Invalid read means that the memory location that the process was trying to read is outside of the memory addresses that are available to the process. size 8 means that the process was trying to read 8 bytes. On 64-bit platforms this could be a pointer, but also for example a long int.

What does invalid write of size 8 mean in Valgrind?

“Invalid write” means that our program tries to write data in a memory zone where it shouldn't. But Valgrind tells you way more than that. It first tells you the size of the written data, which is 1 bytes, and corresponds to the size of a character.

What does invalid write of size mean?

Error message: Invalid write of size 4, means possible an integer or pointer on 32bits platform was stored in a memory that is not allocated with malloc() or on the stack.

What could be an error message displayed by valgrind?

Valgrind reports two types of issues: memory errors and memory leaks. When a program dynamically allocates memory and forgets to later free it, it creates a leak. A memory leak generally won't cause a program to misbehave, crash, or give wrong answers, and is not an urgent situation.


1 Answers

Here

char *url = malloc((length+1)*sizeof(char));
url = '\0';
strncat(url, space, length);

you immediately lose the malloced memory by setting url to NULL. Note that '\0' is 0, which is a null pointer constant. And then you try to strncat something to an invalid memory location.

You probably meant to set

*url = '\0';

there.

like image 146
Daniel Fischer Avatar answered Sep 28 '22 11:09

Daniel Fischer