I'm struggling with this piece of code. As the name suggests, function should return array of strings that represents all rotations of a string given as a parameter.
char **str_all_rotations(const char *data)
{
int i = 0; /* Loop counter */
len = strlen(data); /* Len of input */
/******************/
/* malloc memory */
char **all_rotations = (char**)malloc(sizeof(char*)* len);
char *double_data = (char*)malloc(len * 2 * sizeof(char));
for (i = 0; i < len; i++)
{
all_rotations[i] = (char*)malloc(sizeof(char)* len);
}
/*******************/
/* Rotations part */
strcpy(double_data, data);
strcpy(double_data + len, data);
for (i = 0; i < len; i++)
{
strncpy(all_rotations[i], double_data + i, len);
all_rotations[i][len] = '\0';
}
free(double_data); /* Release memory */
return all_rotations;
}
It works fine from algorithmic perspective, but a simple call of this function
char *str = "omgillsetyouonfire";
char **asdf = str_all_rotations(str);
for (int i = 0; i < strlen(str); i++)
{
free(asdf[i]);
}
free(asdf);
fails, because of heap corruption. I can't see whats wrong. How does one even debug this kind of errors ?