Yes, it's an error. We can demonstrate the error by turning the code into a working example, and running it under Valgrind:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *func2(char *str)
{
strcpy(str, "hello!");
return str;
}
int main()
{
char *str, *res;
int len = 10;
str = malloc(len);
res = func2(str);
free(str);
printf("%s", res);
}
The output shows us what happened:
gcc -std=c11 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds 44704791.c -o 44704791
valgrind --leak-check=full ./44704791
==12624== Memcheck, a memory error detector
==12624== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==12624== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==12624== Command: ./44704791
==12624==
==12624== Invalid read of size 1
==12624== at 0x4C2EDA2: strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12624== by 0x4E80D77: vfprintf (vfprintf.c:1637)
==12624== by 0x4E871F8: printf (printf.c:33)
==12624== by 0x1087B5: main (44704791.c:18)
==12624== Address 0x51d7040 is 0 bytes inside a block of size 10 free'd
==12624== at 0x4C2CDDB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12624== by 0x10879D: main (44704791.c:17)
==12624== Block was alloc'd at
==12624== at 0x4C2BBAF: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12624== by 0x10877D: main (44704791.c:15)
It shows us that the printf
at line 18 tried to read from memory that was released at line 17. Additionally, it shows that the memory in question was allocated at line 15.
The moral of the story is that you should release memory when you have finished using it (not before), and that can be difficult to do if you are not clear about whether your functions take ownership of memory passed to them in pointers.