Segmentation Fault in C function -
i trying develop basic shell. shell need c function parse string. new c tried develop basic function , gives me segmentation fault error. please tell me missing.
#include<string.h> #include<stdio.h> void parse(char *msg); int main() { char *msg = "this message"; parse(msg); } void parse(char *msg){ char *mm; mm = msg; char *tok; tok = strtok(mm," "); while(tok == null){ tok = strtok(null," "); printf("%s \n",tok); } }
error message (runtime)
segmentation fault (core dumped)
thanks in advance
msg
points string literal, , attempting modify it. in c, modifying string literals undefined behaviour (in practice, compilers place them in read-only memory).
to fix, turn msg
array:
int main() { char msg[] = "this message"; parse(msg); }
also, there couple of issues while
loop:
1) condition wrong way round;
2) second strtok()
call should appear after printf()
.
void parse(char *msg){ char *mm = msg; char *tok = strtok(mm, " "); while (tok) { printf("%s \n",tok); tok = strtok(null," "); } }
Comments
Post a Comment