I want to change the values of argv
in C, but I'm getting a segmentation fault. Here's the code.
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
for (int i = 1; argv[i]; i++)
{
char *val;
printf("before: %d %s\n", i, argv[i]);
argv[i] = "bar=foo";
printf("after: %d %s\n", i, argv[i]);
char *arg = argv[i];
val = strchr(arg, '=');
*val = '\0';
}
return 0;
}
I'm passing the argument foo=bar
(and try to change it in line 11 to bar=foo
). The output looks like this:
before: 1 foo=bar
after: 1 bar=foo
So, the modification actually takes place, but the line *val = '\0';
causes a segmentation fault.
Can somebody tell me why this is and how I can prevent it?