Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading