I'm coding C lib functions and have a problem about the memory.
For the strcpy()
function:
char *my_strcpy(char *str1, char *str2)
{
int i = 0;
for (; str2[i] != 0; i++)
str1[i] = str2[i];
str1[i] = 0;
return (str1);
}
With the Criterion test below:
#include <criterion/criterion.h>
char *my_strcpy(char *str1, char *str2);
Test(my_strcpy, in_allocated_string)
{
char *src = "Hello World";
char dest[11];
my_strcpy(dest, src);
cr_assert_str_eq(dest, "Hello World");
cr_assert_eq(dest, my_strcpy(dest, src));
}
The destination buffer is smaller than the source so it should not work... But it works. Valgrind or scan build don't give me any error, it compiles and runs without error...
A Makefile for compile and run with test:
SRC = code.c \
SRC_TEST = test.c \
LDFLAGS = -L./lib/my -lmy
OBJ = $(SRC:.c=.o)
CC = gcc
CFLAGS = -W -Wall -Wextra -Werror -fstack-protector -fstack-protector-all -fstack-protector-strong -Wstack-protector
NAME = libmy.a
all: $(NAME)
$(NAME): $(OBJ)
ar rc $@ $^
test: $(SRC) $(SRC_TEST)
$(CC) -fprofile-arcs -ftest-coverage -Isrc/main -DMOCKING $(CFLAGS) $(shell pkg-config --libs --cflags criterion) $^ -o tests
./tests
clean:
rm -rf *.gcda *.gcno *.info $(OBJ)
fclean: clean
rm -f $(NAME)
rm -rf tests
re: fclean all
Is there a solution to detect memory error in a C program?