1

In the code below the result is stack overflow. Though null character is there with both the strings, so the strcpy loop should terminate as the source string has null character. Why stack overflow occurs??

#include <stdio.h>
#include<strings.h>
int main(void) {
    char *str="Hello world";
    char *str1="Good morning";
    strcpy(str,str1);
    printf("%s",str);
    return 0;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Siya
  • 71
  • 1
  • 1
  • 8

1 Answers1

9

The error isn't stack overflow, but modifying a string literal.

str is a pointer that points to a string literal "Hello world", and modifying a string literal is undefined behavior.

Change str to:

char str[100] = "Hello world";
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • Means char *str is by default const char *str?? If so why it doesnt happen in arrays of datatypes other than char? – Siya Sep 22 '14 at 10:14
  • @Siya Read [What is the difference between char s\[\] and char *s in C?](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c) – Yu Hao Sep 22 '14 at 10:24