Home > Software design >  Access violation with strcpy in c
Access violation with strcpy in c

Time:09-28

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

#define SIZE_OF_RECORD 100


void main()
{
   char lineBuffer[SIZE_OF_RECORD];
   memset(lineBuffer, '\0', (SIZE_OF_RECORD - 1) * sizeof(char));


   strcpy(lineBuffer, "testing"); strcat(lineBuffer, ',');  //exception thrown here Exception thrown at 0x00007FFCB7B5D1CB (ucrtbased.dll) in PA_2.exe: 0xC0000005: Access violation reading location 0x000000000000002C.
   printf("line buffer after assemble line \n%s", lineBuffer);
    
}

I do not understand. The string as it is declared should not be read only right? Why cant I change it?

CodePudding user response:

The function strcat expects two arguments of the type char * but you are calling it passing an object of the type int

strcat(lineBuffer, ',');

The function strcat is declared like

char *strcat(char * restrict s1, const char * restrict s2);

At least write

strcat(lineBuffer, ",");

using the string literal "," instead of the integer character constant.

Also it is unclear why in this call

memset(lineBuffer, '\0', (SIZE_OF_RECORD - 1) * sizeof(char));

you are using the expression (SIZE_OF_RECORD - 1) instead of SIZE_OF_RECORD. You could write

memset(lineBuffer, '\0', sizeof(lineBuffer ));
  • Related