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?

2
  • 4
    You think Tmp has enough memory to hold your string? Commented Oct 26, 2016 at 7:50
  • @andy please don;t add thank you and alike, it was removed for a reson. :) Commented Oct 26, 2016 at 8:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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()

1 Comment

Or use a VLA: char Tmp[ strlen(sNext1) + 1 ];

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.