Segmentation on vprintf.c

I am the second cs student, still not as good at programming as I would like. We are working with OS161 in C this year.

To the problem, I have to write a C program that can take commands as arguments and return them back. No problem. I used to do this in other languages. Here is the code I tried:

#include <stdio.h> int main (int argc, char *argv[]) { int i = 0; printf("\ncmdline args count=%s", argc); /* First argument is executable name only */ printf("\nexe name=%s", argv[0]); for (i=1; i< argc; i++) { printf("\narg%d=%s", i, argv[i]); } printf("\n"); return 0; } 

This only compiles with gcc, but when I run it, I get Segmentation Fault. I run it with gdb and this is what I get:

 Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7abc493 in _IO_vfprintf_internal (s=0x7ffff7dd97a0, format=<value optimized out>, ap=0x7fffffffe3f0) at vfprintf.c:1623 1623 vfprintf.c: No such file or directory. in vfprintf.c 

When I comment on printf instructions, it works, but obviously then it will not do what I need. As far as I can tell, this is a printf problem, but why? I looked through it and I included the right header. It’s hard for me to imagine that something is really wrong with vfprintf.c, since all this happens in my VM school, which I enter. If anyone could throw a bone at me, I would really appreciate it. Thanks!

Change, as you can see, my conversion specifier is incorrect. That was the whole problem.

+5
source share
1 answer

argc is an integer, but you told printf use the %s format.

 printf("\ncmdline args count=%s", argc); 

Since you used %s , printf treats the argc value as the memory address from which it is trying to extract characters in the string, resulting in a segmentation error.

Change the format to %d :

 printf("\ncmdline args count=%d", argc); 
+10
source

Source: https://habr.com/ru/post/1234338/


All Articles