Adobe Interview Question
Software Engineer / DevelopersCountry: India
Using ** and & will just give you undefined behavior. The compiler may actually place the second string in read-only memory. If you try to use ** and & you will get a memory error.
Hello, Where is the ROM concept will come.
ROM is permanent storage device. Always variables are stored in Mainmemory i.e RAM. since it is local variable to it is stored in Stack segment.
char s[] = "/root//foo/bar" ;
char *str = "/root//foo/bar" ;
-> s is a constant pointer it will point to base address of first element, we can't change address but we can change value.
ex: scanf("%s",s);
strcpy(s,s1);// if s1 has some address of string
s[0]='d',s[1]='j'........
-> str is a pointer to an constant integer, string will store in Read only memory in Data segment that's why we can't change value but we can change address.
str=malloc(size_t size);
scanf("%s",str);
Essentially the second statement is asking compiler to allocate memory for the string literal, which is read only. For a complete explanation please refer to the anwers on stack overflow question -
stackoverflow.com/questions/1577765/why-must-a-pointer-to-a-char-array-need-strcpy-to-assign-characters-to-its-array
char *str = "foo"; is an unmodifiable string as described by the C standard. Any attempt to modify it results in undefined behavior. Undefined behavior means the behavior of your program is no longer described by the C standard so your implementation may do whatever. In this case, it gives "segmentation fault." Another valid response would be: "system("rm -fr /");" if you were on a *nix based system.
#include<stdio.h>
void main()
{
char s[]="nimesh";
char *str="nimesh";
printf("s=%s\n",s);
printf("str=%s\n",str);
s[1]='a'; // this works fine
str[1]='a'; // this gives segmentation fault as it is constant string and stored in Read only area....
printf("s=%s\n",s);
printf("str=%s\n",str);
}
the 2nd declaration (char *str) declares a pointer to a char... this pointer is placed on the current memory stack but the data itself ("/root//foo/bar") is stored elsewhere, not on the current stack and not at that same location. So you cannot (should not) change the value using str[in1] = str[in2]. It will lead to seg fault as you have rightly noticed.
- JustCoding October 23, 2012But if you have to change the value, you use double indirection (using ** or &) and make the change.