1
#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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Compiler warnings can help you avoid issues like these. https://godbolt.org/z/csfKGWaza – Retired Ninja Sep 27 '22 at 21:27
  • Besides the obvious warning tat your compiler should throw at you, avoid the use of `strcpy` and `strcat`. Usually `snprintf` does a better job, but if you must, use `strncpy` and `strncat`. In either case, pass the size of the buffer. – Cheatah Sep 27 '22 at 21:32
  • I would strongly recommend to use `strncpy` instead of `strcpy` to reduce the changes of having a buffer overflow attack to your code. – acarlstein Sep 27 '22 at 21:36

1 Answers1

1

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 ));
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335