I am with a project to recreate C functions to learn and I am with the memset function which when trying to recreate its operation gives me the following error
*** stack smashing detected ***: <unknown> terminated
[1] 3679 abort (core dumped) ./a.out
This is the code and my main
#include <stdio.h>
void *ft_memset(void *str, int c, size_t n)
{
char *ptr;
ptr = str;
while (n)
{
*(ptr++) = (unsigned char)c;
n--;
}
return (str);
}
int main()
{
char str[] = "";
ft_memset(str, 4, 10);
printf("%s", str);
}
I present you with a fixed-size array of length 1. Its content is limited to a null character:
And here you try to modify 10 positions of it:
It's like pretending that a car fits into a Tupperware...
You have to create an array of sufficient size for the function to do its job:
You have to reserve space for 11 characters because don't forget that in C, character strings always end with
'\0'
.We fixed this and... surprise!!! the program still does not show anything!!!
That's because, according to an ASCII table, character 4 is not printable . Replace
4
with'4'
and try again:Final note Finally, the error that appears occurs because fixed-size arrays are stored on the program's stack... and by trying to write several positions outside the array you are writing outside the limits of said stack... that's it The operating system detects it and kills your program so that it doesn't corrupt memory that doesn't belong to it.
In C there are no automatic processes that meet your expectations.
There would be, however, a possible solution and it involves using pointers and dynamic memory.
The first thing would be to change
str
it to be a pointer. It is very important to initialize it to0
or toNULL
, which is the same:To resize the managed memory we have to use
realloc
:It is important, as you can see, not to overwrite
str
directly. We must verify that itrealloc
has finished successfully because if we do not lose the ability to recover the previously reserved memory.The problem with it
realloc
is that it's not automatic and it's also not something you should put in your functionft_memset
since the original function doesn't juggle memory. The original version assumes that you know what you're doing and that you're careful not to write outside the bounds of the array.a not serious error but bad in terms of programming is to copy a void pointer to char remember that they are different types therefore you must make an explicit cast, another error is that you try to modify 10 positions in an array of length 1 therefore it happens a buffer overflow, sometimes it appears as (sig fault) or (core dump) modify your code a bit to make it work check it and analyze the differences. I hope this example helps you. Good luck