-1

When I run this code I get the error segmentation fault (core dumped)

#include<stdio.h>
int main(int argc, char *argv[]) {
  int i = 0;
  printf("\n cmdline arg counts = %s ", argc);
  printf("\n exec name = %s ", argv[0]);
  for (i=1; i<argc; i++) {
    printf("\n arg %d = %s" , i, argv[i]);
  }
  return 0;
}

Tell me how to solve this. I am passing arguments.

closed as off-topic by Stephen Kitt, Julie Pelletier, Anthon, Scott, Archemar Sep 6 '16 at 9:19

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Julie Pelletier, Scott, Archemar
If this question can be reworded to fit the rules in the help center, please edit the question.

  • How this is execute? What command is used to execute it? Please share it. – Pawel Sep 6 '16 at 4:29
  • 4
    The error is so obvious that it will get closed as a typo if we move it to stackoverflow.com, where it belongs. Your first printf considers argc as a string which makes it refer to that address which obviously doesn't exist. Use %d instead of %s. – Julie Pelletier Sep 6 '16 at 4:54
  • beside, on ubuntu I get a clear wrning at compile time. – Archemar Sep 6 '16 at 9:19
2

Your problem lies in the line:

printf("\ncmdline arg counts = %s ",argc );

You use %s (instead of %d) form printing argc, thus interpreting argc as a pointer to a string. This makes printf try to read a string in a protected space. Change the line to:

printf("\ncmdline arg counts = %d ",argc );

And all is well

Not the answer you're looking for? Browse other questions tagged or ask your own question.