Violation of access rights when writing to an address in C. The strcat function

There is a simple mp3 player:

#include <windows.h>
#include <Mmsystem.h>
#pragma comment(lib,"winmm.lib")
#pragma warning(disable : 4996)
#include <stdio.h>
#include <string.h>

char *types = " type mpegvideo alias myFile";
char *open = "open ";

char* compound(char *path) {
    strcat(path, types);
    open = malloc(500);
    open = "open ";
    //printf(open);
    //printf("\n");
    //printf(path);
    strcat(open, path);
    return open;
}

void playMedia() {
    char *path = malloc(100);
    printf("Enter a path to your music: ");
    scanf("%s", path);

    mciSendString(compound(path), NULL, 0, 0);
    mciSendString("play myFile wait", NULL, 0, 0);
    mciSendString("close myFile", NULL, 0, 0);

    if (getch() != 113) {
        open = "";
        path = "";
        playMedia();
    }
}

int main()
{
    playMedia();
    return 0;
}

And on this line strcat(open, path); an error occurs:

Необработанное исключение по адресу 0x669EEA19 (ucrtbased.dll) в Project4.exe: 0xC0000005: нарушение прав доступа при записи по адресу 0x00C27B3D.

Why does this error occur? How can solve it?

Author: Harry, 2019-02-18

1 answers

open = malloc(500);

Yeah, now open points to a specially allocated 500-byte memory space...

open = "open ";

And now-to the place in the memory where the word open is written...

strcat(open, path);

And now we want to add it to a place where no one has reserved the memory. And 500 bytes is now just a leak...

It's strange that you know about strcat, but you don't try to do the right thing and write strcpy(open,"open "); instead of open = "open ";...

 1
Author: Harry, 2019-02-18 17:59:23