char* s1; strcpy(s1,"smilehihi"); s1[6] = 'a'; 

When I compile, VS do not have any errors. But in the runtime, my code makes mistake. I think I do not really understand about strcpy

15

4 Answers

The main issue here is not the strcpy() function but the fact that you don't allocate any memory for the string itself. If I were you, I would do something like

char* s1=(char*)malloc(SIZE); // the SIZE is the predefined maximum size of your string strcpy(s1,"smilehihi"); s1[6] = 'a'; 

Edit:

Just as an advice, consider using stpncpy(). It helps to avoid buffer overflow, and, in your case, will help you avoid exceeding the maximum size of char*

char * stpncpy(char * dst, const char * src, size_t len); 
4

The problem is that you have not allocated any space for what you wish to store in s1: "smilehihi". You declare s1 as a pointer variable, but it needs something to point at. You can allocate space by using the new operator.

char* s1 = new char[stringLength + 1]; //stringLength = length of string stored // + 1 to hold null terminator character strcpy(s1, "smilehihi"); s1[6] = 'a'; 

You have to declare #define _CRT_SECURE_NO_WARNINGS at the top of your main file to avoid an error during compilation due to strcpy() being deprecated.

2

You need to allocate variable first by malloc() or by using the keyword new . Also deallocate the memory at the end

At first you should allocate char* s1.

char *s1 = new char[9]; // C++ version 

or you can you use C version:

char *s1 = (char*)malloc(9); 

Then you can use following code:

strcpy(s1, "smilehihi"); s1[6] = 'a'; 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy