I’m writing a function that returns the first n (n <= strlen(src)) characters of a string.
char* substring(char *src, int n)
{
char *substr;
int i;
for (i = 0; i < n; i++)
*substr++ = *src++;
src = src - n;
*substr = '\0';
return substr - n;
}
This function returns the right answer when called only once but returns a Seg Fault when it is called more than once.
No memory is allocated for
substrand the function therefore deferences an uninitialized pointer and is writing to memory where it is not supposed to resulting in undefined behaviour. The fact it works the first time is complete chance.Allocate memory for
substr:Note that the caller of
substring()mustfree()the returned buffer.