Below I wrote a function_getstr()
, to get string in input without using scanf
. Running valgrind, however, results "Invalid write of size 1" error. This happens for each input. What causes this error?
char *_getstr(){
char *str = NULL;
int bufsize = 0, c = 0;
do {
c = getchar();
if (c != '\n'){
str = realloc(str, (bufsize + 1)*sizeof(char));
str[bufsize++] = c;
}
} while (c != '\n');
str[bufsize] = '\0';
return str;
}
In main I do that:
char *s1 = _getstr();
The output of valgrind when I insert the input is this:
Insert of the first string: hello
==6830== Invalid write of size 1
==6830== at 0x109294: _getstr (changeJOIN.c:43)
==6830== by 0x10919B: main (changeJOIN.c:15)
==6830== Address 0x4a419b4 is 0 bytes after a block of size 4 alloc'd
==6830== at 0x4839D7B: realloc (vg_replace_malloc.c:826)
==6830== by 0x109264: _getstr (changeJOIN.c:39)
==6830== by 0x10919B: main (changeJOIN.c:15)
When you add the terminating null byte, str
points to bufsize
bytes, so str[bufsize] = '\0';
writes one element past the end of allocated memory. This is what valgrind it complaining about.
You need to allocate one more byte before adding the null terminator.
str = realloc(str, (bufsize + 1)*sizeof(char));
str[bufsize] = '\0';