pointers - Why Do I Get a Segmentation Fault with this C Code? -


this code gives me segmentation fault:

char *s1 = "string 1", *s2 = "string 2"; void swap(char **, char **);  int main(void) {     swap(&s1, &s2);     return 0; }  void swap(char **p, char **q) {     char **tmp;      *tmp = *p;     *p = *q;     *q = *tmp; } 

but if change body of last function code doesn't make problems:

    char *tmp;      tmp = *p;     *p = *q;     *q = tmp; 

i don't understand why getting segmentation fault first code. in advance.

your tmp pointer uninitialized , dereference in next line. that's undefined behaviour, includes possibility of segfault.


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -