Search code examples
cdynamic-memory-allocationc-stringssizeofstrcpy

Question about strcpy using char pointer in C


I'm doing some programming with C, and I have a minor problem using strcpy.

char* file="It has something inside"
int size= sizeof(file);
char* file_save = malloc(sizeof(char)*size);
strcpy(file_save,file);

My code stopped working in the last line. What can be the problem here?

It seems like something went wrong outside this part of the code. It works perfectly well if I change sizeof into strlen in the online gdb, but it still stops in the strcpy line on my computer's VS code. Thank you for helping me.


Solution

  • As comments suggest, the size is the size of variable char pointer which is probably 8 if you are working on a 64-bit machine. So you need the size of string the file is pointing to. You can get that like below:

    int size = strlen(file) + 1;
    

    The strlen returns the number of bytes this string has. Every string is finished by a null terminator \0. While you are writing in a file it doesn't matter which bytes are for the string and which is the null terminator so you need to count both.