Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation on on vprintf.c

Tags:

c

unix

gcc

gdb

I'm a second year cs student, still not nearly as proficient at programming as I would like to be. We're working with OS161 in C this year.

To the problem, I'm supposed to write a C program that can take command like arguments and echo them back. Ok, no problem. I've done this in other languages before. Here's 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 compiles just fine 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 out the printf statements, it runs, but obviously then won't do what I need it to. As far as I can tell, it is the printf statements that are the problem, but why? I looked it up and I included the right header. It's hard for me to imagine that there is actually something wrong with vfprintf.c, since this all takes place on my school's VM that I ssh into. If anyone could throw me a bone, I'd really appreciate it. Thanks!

Edit, as you can see, I have the wrong conversion specifier. That was the whole problem.

like image 699
He-Man Avatar asked Oct 23 '15 01:10

He-Man


1 Answers

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

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

Because you used %s, printf treats the value of argc as a memory address from which it tries to fetch the characters in the string, which resulted in the segmentation fault.

Change the format to %d:

printf("\ncmdline args count=%d", argc);
like image 159
Warren Weckesser Avatar answered Oct 12 '22 22:10

Warren Weckesser