Home > Net >  Strange characters in String C
Strange characters in String C

Time:10-29

I was writing a simple compiler just for fun and I wanted each line to have proper indentation.

So I wrote a function that returns an array of characters with some white-spaces depending on the number.

The problem is that when the array is generated some characters seem to be wrong at the time of writing the in the file or just printing. I think they are taken from a memory location with some information because I saw a fragment of a file path.

I made an example code that has the same problem

int num = 0;
char *tabs;
for (; num < 20; num  )
{
    tabs = malloc(num);
    memset(tabs, '-', num);
    printf("%d | %sEND\n", num, tabs);
}

(I suppose it's not the best code but I'm a beginner in C)

Output:

0 | Çc▬END
1 | -s▬END
2 | --▬END
3 | ---END
4 | ----END
5 | -----END
6 | ------END
7 | -------END
8 | --------P☺▬END
9 | ---------☺▬END
10 | ----------▬END
11 | -----------END
12 | ------------END
13 | -------------END
14 | --------------END
15 | ---------------END
16 | ----------------END
17 | -----------------END
18 | ------------------END
19 | -------------------END

The characters are different everytime I run the program.

If instead of memset I use a for loop to set each character the result will be the same.

I read that memset would solve the problem but I didn't.

CodePudding user response:

The dynamically allocated character array tabs after using memset

tabs = malloc(num);
memset(tabs, '-', num);

does not contain a string.

So using the conversion specifier %s in the call of printf with this array invokes undefined behavior.

You could write instead

tabs = malloc(num   1);
memset(tabs, '-', num);
tabs[num] = '\0';

Another approach is just to change the call pf printf the following way

printf("%d | %.*sEND\n", num, num, tabs);

Pay attention to that the for loop produces numerous memory leaks because the allocated memory in each iteration of the loop is not freed.

  • Related