Program aborts when using strcpy on a char pointer? (Works fine on char array)
Asked Answered
E

6

9

I'm perplexed as to why the following doesn't work:

char * f = "abcdef";
strcpy(f, "abcdef");
printf("%s",f);

char s[] = "ddd";
strcpy(&s[0], "eee");
printf("%s", s);

In both examples strcpy received a char * yet on the first example it dies a horrible death.

Exceptional answered 13/4, 2011 at 7:43 Comment(0)
S
11

"abcdef" and "ddd" are string literals which may reside in a read-only section of your address space. char s[] = "ddd" ensures this literal is copied to stack - so it's modifiable.

Suspensor answered 13/4, 2011 at 7:46 Comment(0)
P
6

char * f = "abcdef"; defines a char pointer to "abcdef" which is located in read-only area so you can't write to this place

char s[] = "ddd"; defines a char array on the stack which is writable.

Pollitt answered 13/4, 2011 at 7:48 Comment(0)
I
5

In the first example, you have a pointer to a string literal. This pointer should really be const char *, because any attempt to modify a string literal is undefined behaviour. However, for legacy reasons allows you to use a char * to point at it. But you still shouldn't be trying to modify it.

In the second version, you have a bog-standard array, whose contents happen to be initialised to be equivalent to your string. This is modifiable, as it's your array.

Indicate answered 13/4, 2011 at 7:46 Comment(0)
T
4

The first example is a char * to a character literal (a literal is "something"). Character literals are read-only, and attempting to write to them can result in crashes. Your first pointer should really be const char *f = "abcdef";, which strcpy won't take.

Thyroiditis answered 13/4, 2011 at 7:46 Comment(0)
T
2

The statement char * f = "abcdef" assigns a point in memory to the literal string "abcdef", however it will refuse to let you modify its contents until the memory is dynamically allocated - it's equivalent to a const char.
All you're doing is creating a pointer in memory and then writing over the next 6 bytes, which is illegal in C.

Towards answered 13/4, 2011 at 7:47 Comment(0)
H
2

String literals are considered readonly by most compilers, so the memory where they reside can be marked as readonly, resulting in a runtime error.

To make it work, do the following:

char * f = strdup("abcdef");
strcpy(f, "abcdef");
printf("%s",f);
free(f);

This creates a modifiable copy of the string in the heap memory, which needs to get freed at the end of your program of course.

Humanitarianism answered 13/4, 2011 at 7:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.