Process returned -1073741819 (0xC0000005) in C

0

I'm making a program in which I need to first convert an integer to a string (char array) for that I used itoa() function which is working fine, after that I want to also concate it to a string, but it's not working and giving me following error:

Process returned -1073741819 (0xC0000005)

My Code:

int main(int argc, char *argv[]) {
    char *scoreText = "Score: ";
    char *msg;
    int num = 1888;
    itoa(num,msg,10);
    printf("%s\n", msg);
    printf("%s\n", scoreText);
    strcat(scoreText, msg);
    printf("%s\n", scoreText);
}
c
arrays
pointers
malloc
strcat
asked on Stack Overflow Apr 22, 2019 by Usman Developer

1 Answer

3

0xC0000005 is basically the Windows variant of a segmentation violation (usually caused by trying to use memory you shouldn't be using).

One of your problems lies here, with the code:

char *msg;

This creates a pointer to memory but does not actually allocate any memory for the pointer to point to. As it's an object with automatic storage duration, it will contain some arbitrary value, which is likely to be pointing somewhere other than you need.

What you should do instead is something like:

char msg[100];

which will both allocate 100 bytes for the buffer and ensure that the identifier msg points to that buffer.


Another problem is:

char *scoreText = "Score: ";
strcat(scoreText, msg);

The first line creates a character pointer and points it at the first character of the string literal "Score: ". It is undefined behaviour to attempt to modify string literals (such as by appending a string to them). To fix that issue, you have to have memory that is allowed to be modified, such as with:

char scoreText[200] = "Score: ";

This effectively gives you a 200-byte buffer initially populated with the string (as opposed to a pointer to the string literal), to which you can safely append your (up to) 100-byte msg string. It's effectively the same as

char scoreText[200];
strcpy(scoreText, "Score: ");

And, just one final point. You should be aware that itoa is not standard C but the way you're using it can be easily done with:

sprintf(msg, "%d", num);

Final working code below, though no doubt more improvements could be made:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char scoreText[200] = "Score: ";
    char msg[100];
    int num = 1888;
    sprintf(msg, "%d", num);
    printf("%s\n", msg);
    printf("%s\n", scoreText);
    strcat(scoreText, msg);
    printf("%s\n", scoreText);
}
answered on Stack Overflow Apr 22, 2019 by paxdiablo • edited Apr 22, 2019 by paxdiablo

User contributions licensed under CC BY-SA 3.0