647 views
0 votes
0 votes

i am doing strcpy from a larger string into a relatively smaller string using two ways.According to me both the methods allocate space statically(as i am not using any malloc or calloc in either of my cases). but still method1 gives me segementation fault(in ubuntu) or just cracshes the exe generated (in windows),i.e i am trying to access area out of my way, while method2 doesn't . why?

method 1:

char *a = "hi";
char *b = "hisi";
try
{
    strcpy(a, b);
    cout << "all ok";
}
catch (exception e)
{
    cout << "error";
}

method2:

char a[3] = "hi";
char b[5] = "hisi";
try
{
    strcpy(a, b);
    cout << "all ok";
}
catch (exception e)
{
    cout << "error";
}

1 Answer

Best answer
2 votes
2 votes
char *a = "hi";

Here you are declaring a pointer a, and assigning a value to it which is the address of "hi". "hi" is a string literal here meaning it is nothing but a constant. So, compiler stores this string in a READ ONLY (RO data segment) region as string literals are not meant to be modified. So, if we try to modify this memory region (by strcpy or any other means), OS won't allow it. 

char a[3] = "hi";

Here variable a is allotted memory for storing 3 characters and the characters 'h', 'i' and '\0' are stored to it. Since scope of a is "auto", this allocation happens in stack and programmer is free to modify this memory location with in the function. But there is memory for only 3 characters. If using strcpy more than 3 characters are assigned, behaviour is undefined- sometimes it might work if there are some unused memory given by the compiler, sometimes it might crash due to memory corruption by writing to unallocated memory or sometimes program might give wrong output by modification of unintended memory locations. 

selected by

Related questions

0 votes
0 votes
1 answer
1
tempUser1 asked Feb 15, 2016
999 views
Like the question says, what is the difference between Gate SCORE and marks out of 100? Why there are 2 different marks?
0 votes
0 votes
1 answer
3
Isha Karn asked Dec 8, 2014
13,159 views
int x=5; void f() { x = x+50; } void g(h()) { int x=10; h(); print(x); } void main() { g(f()); print(x); }1) what is output if code uses deep binding?2)what is the output...