The following is a C program written to print a different combination of characters in a string.
This is not an efficient way, as this algorithm creates many extra lines. However, my question is NOT about how to solve this problem more efficiently.
The program works (albeit inefficiently) and prints a different combination of line characters (correctly). But when I try to freecreate additional lines that arise, I run into a problem. freethat causes the problem is at the end of the thr function recur_printc(it is commented out).
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 3
void recur_printc(char *, int, char *);
int main()
{
char str[] = "abc";
char *print_arr = malloc(N * sizeof(char));
recur_printc(print_arr, 0, str);
free(print_arr);
return 0;
}
void recur_printc( char *print_arr, int index, char *remaining)
{
int i, j, rem_len, index_4_next;
if(strlen(remaining) == 1)
{
print_arr[index] = remaining[0];
for(i=0; i<N; i++)
{
printf("%c",print_arr[i]);
}
printf("\n");
return;
}
else
{
rem_len = strlen(remaining);
for(i=0; i<rem_len; i++)
{
print_arr[index] = remaining[i];
char *remaining_for_next = malloc((rem_len-1) * sizeof(char));
index_4_next = 0;
for(j=0; j<rem_len; j++)
{
if(j != i)
{
remaining_for_next[index_4_next] = remaining[j];
index_4_next++;
}
}
recur_printc(print_arr, index+1, remaining_for_next);
remaining_for_next = NULL;
}
}
}
When I ran this program in gdb, I noticed that when i=1for the first instance recur_print, malloca strange thing happens with .
When this line is completed:
char *remaining_for_next = malloc((rem_len-1) * sizeof(char));
rem_len-1 2, malloc 3 , , - strlen ( 3 2). , . ( , free().)
gdb:
42 char *remaining_for_next = malloc((rem_len-1) * sizeof(char));
(gdb) print remaining_for_next
$3 = 0x0
(gdb) n
43 index_4_next = 0;
(gdb) print remaining_for_next
$4 = 0x602030 "@ `"
(gdb) print rem_len-1
$5 = 2
(gdb) q
. , , comibnation ( ) . , , remaining_for_next (, malloc ).