Phyllis Vance
Phyllis Vance

Reputation: 13

Exception: Access violation writing location when using strcpy_s

When I compile the following code, I get this exception:

Unhandled exception at 0x0FA8E90F (ucrtbased.dll) in console.exe: 0xC0000005: Access violation writing location 0xFFFFFFCD

 void test()
{
      char *type = malloc(sizeof(char) * 256);
      strcpy_s(*type, 7,"Laptop");
}

I have to mention that I am a begginer in working with dynamic implementation and pointers. I am also not allowed to use a static implementation.

In the above snippet I also tried different implementations as: replacing the following line:

  strcpy_s(*type, 7,"Laptop");

with this line:

  strcpy(*type, "Laptop");

but the result was the same. Any suggestion for my problem?

Thank you in advance.

Upvotes: 0

Views: 1145

Answers (1)

TheoretiCAL
TheoretiCAL

Reputation: 20571

Instead of strcpy_s(*type, 7,"Laptop"); you want strcpy_s(type, 7,"Laptop");

strcpy_s assumes the first argument is a pointer for the destination of the data, as per the signature: errno_t strcpy_s(_CHAR *_DEST, size_t _SIZE, const _CHAR *_SRC).

In your code you were dereferencing the pointer type when passing it to strcpy_s, which is the problem. Because the function expects a char * as the first argument, when you pass *type instead of type, it is as if you passed a char which is then incorrectly interpreted as a pointer (memory location). When strcpy_s tries to write to this invalid memory location, it throws the access violation exception you see. Note this is the same reason strcpy was giving you the same result.

Upvotes: 1

Related Questions