Reputation: 8688
int main() {
char **k;
char *s ="abc";
char *b ="def";
*k = s;
}
//Why does this produce segmentation fault? Shouldn't everything be store on the stack without any problems?
Upvotes: 2
Views: 135
Reputation: 38967
Ok, I hope I don't get beaten up with with any slight error... here is my attempt to explain it as fully as I can.
With an ordinary char* it will point to a char.
with a char** it points to a pointer that points to a char. That *k value is on the heap and not the stack.
i.e. like this:
stack (1) heap (2) heap or ... (3)
+-----+ +-----+ +----+
|char*| -> |char*| -> |char|
+-----+ +-----+ +----+
Now char*'s are not really strings but they are treated as blocks of contiguous printable characters in memory that are terminated by a null or zero byte. So the string would be stored and be referenced at (3)
So to fix your code you'll want to allocate space for a char* (not a char).
i.e. put
k = (char**)malloc(sizeof(char*));
before the line
*k = s;
Not that it's a good code, But it shouldn't crash.
Upvotes: 2
Reputation: 104100
Alexander is correct, you're dereferencing k
with *k = s;
. Your initialization of char *s="abc";
may look the same, but it is syntactic sugar for the longer: char *s; s="abc";
Upvotes: 1
Reputation: 46657
k
has no defined value yet, so dereferencing it (*k
) causes undefined behaviour. If you add an initialization, i.e. k = &b;
, *k = s;
will work afterwards.
Upvotes: 4