1

I have got a basic question about the following code:

int main() {
    char *sNext1="DABCD";
    char Tmp[]="";
    strcpy(Tmp, sNext1);
    return 0;
}

There is a error happened in "strcpy" when I run it. It seems that it doesn't allow me to copy a string into a dynamic array. Does anyone know what causes this error? And how can I fix it?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Andy Lu
  • 29
  • 1
  • 7

2 Answers2

5

The problem here is with

 char Tmp[]="";

here, Tmp is not an dynamic array, it's an array with exactly one element (initialized via the initializer). When you use this as destination for strcpy(), you're overrunning the buffer. Basically, your code tries to access out of bound memory, which invokes undefined behavior.

Related, quoting C11, chapter §7.24.2.3, strcpy(), emphasis mine

The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. [...]

and then, for "String function conventions", §7.24.1,

[....] If an array is accessed beyond the end of an object, the behavior is undefined.

Solution: You need to ensure that Tmp has enough memory to hold the content to be copied into it, including the null terminator.

That said, for a hosted environment, int main() should at least be int main(void) to be conforming to the standard.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

Allocate memory to Tmp before copying the string to Tmp.

Tmp is an character array of size 1.

Allocate memory dynamically as shown below. (If you are trying to do dynamic memory allocatio)

char *Tmp = malloc(strlen(sNext1) + 1);

Then try doing strcpy()

Gopi
  • 19,784
  • 4
  • 24
  • 36