Strange characters preceding string in C

My processes array is filled with the following strings:

#define MAX_LINES 100
#define MAX_LEN 100

char processes[MAX_LINES][MAX_LEN];
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

0 3 * * *      daily-backup
15 4 * * sun   weekly-backup
0 10 22 7 mon  deep-thought
59 16 16 8 *   submit-project
0 2 1 * *      send-monthly-newsletter

I’m using the following code to clean it up:

    char times[clean_line][100];
    
    for (int z=0;z<clean_line;z++) {
        int x = 0;
        int space_counter = 0;
        while ( (processes[z][x] != '\0') && (space_counter < 5) ) {
            if (processes[z][x] == ' ') {
                strcat(times[z], "/");
                space_counter++;
                x++;
            }
            else {
                strncat(times[z], &processes[z][x], 1);
                x++;
            }
        }
    }

That code produces this:

0/3/*/*/*/
15/4/*/*/sun/
0/10/22/7/mon/
����59/16/16/8/*/
K��U0/2/1/*/*/

Those first 3 lines look fine, but the last 2 have bad characters at the start.
Any ideas?

>Solution :

At least this issue:

strcat(times[z], "/"); is undefined behavior (UB) as times[z] is not certainly a string, as required.

Initialize/assign times[] to start them off as strings by at least zeroing the first element: times[i][0].

// char times[clean_line][100];
char times[clean_line][100] = { 0 };  // Fill all with zeros.

// or
char times[clean_line][100];
for (int z=0;z<clean_line;z++) {
  times[z][0] = '\0';
}

Leave a Reply