Strcpy does not work correctly with char arrays

-3

I get the following output when I run the code below:

Matrikel: 01717
Process finished with exit code -1073741571 (0xC00000FD)

Code:

char infos[255];
char matrikelnr[5];

sprintf(matrikelnr, "%d", s->matnr);
size_t n = strlen(matrikelnr);

while (n != 5) {
    memmove(matrikelnr + 1, matrikelnr, 5);
    matrikelnr[0] = '0';
    n = strlen(matrikelnr);
}

printf("Matrikel: %s", matrikelnr);
strcpy(&infos[0], matrikelnr);
printf("DEBUG");

I already tried: strcpy(infos[0], matrikelnr); and strcpy(infos[0], matrikelnr);

The strcpy seems to have a problem. Could you please help me with the solution?

Thanks already!

arrays
c
char
strcpy
asked on Stack Overflow May 15, 2021 by silasmartin • edited May 15, 2021 by chqrlie

2 Answers

1

The main problem of your code is that you don't provide enough room for the string-terminating character '\0'. Each C string needs this to mark the end of the string. If you need to store strings with 5 characters, the variable needs to provide space for 6 characters.

However, your task can be solved much simpler, if you use standard formatting facilities. Change your call of sprintf() like this:

char matrikelnr[5 + 1];

sprintf(matrikelnr, "%05d", s->matnr);

The '0' is for using zeroes as filling character, and the '5' for a width of (at least) 5 characters.

I hope that your numbers are never greater than 99999.

Please read the documentation for details, and consider to use safer functions like snprintf().

answered on Stack Overflow May 15, 2021 by the busybee • edited May 15, 2021 by the busybee
0

I think, it is almost impossible to tell you exactly what causes the problem with the given code, but I could give you some advice from my experience. Some functions in c (e.g. memmove(), strcpy()) does not have perfect design as their behavior is undefined according to context. So first, make sure NULL Bytes are set correctly in your variables(that can cause many problems in c when it comes to char*). I think you don't have null bytes in your char arrays at right place, that causes problem for string functions(function cannot understand when to stop while copying string from one place to another). ps. I mean char* when I say string you know. This kind of problems also cause "segmentation fault" quite often.

answered on Stack Overflow May 15, 2021 by otokkk

User contributions licensed under CC BY-SA 3.0