My resize program works per cs50 check, but it has a segmentation fault per valgrind. It appears to be with the atoi function, but I'm lost as to why

    ==750== Memcheck, a memory error detector
==750== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==750== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==750== Command: ./resize
==750== Invalid read of size 1
==750==    at 0x517A517: ____strtol_l_internal (strtol_l.c:298)
==750==    by 0x5176F5F: atoi (atoi.c:27)
==750==    by 0x4008C5: main (resize.c:18)
==750==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==750== Process terminating with default action of signal 11 (SIGSEGV)
==750==  Access not within mapped region at address 0x0
==750==    at 0x517A517: ____strtol_l_internal (strtol_l.c:298)
==750==    by 0x5176F5F: atoi (atoi.c:27)
==750==    by 0x4008C5: main (resize.c:18)
==750==  If you believe this happened as a result of a stack
==750==  overflow in your program's main thread (unlikely but
==750==  possible), you can try to increase the size of the
==750==  main thread stack using the --main-stacksize= flag.
==750==  The main thread stack size used in this run was 8388608.
==750==     in use at exit: 0 bytes in 0 blocks
==750==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==750== All heap blocks were freed -- no leaks are possible
==750== For counts of detected and suppressed errors, rerun with: -v
==750== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault

The error is in a .c file I don't even recognize, so I'm not sure how to start finding it. I'm assuming it's somehow in my use of atoi? Here are lines 17-27 of my code (can post more as needed) since it says the error is "by" these lines.

    // ensure proper usage and calculator sizefactor
int sizefactor = atoi(argv[1]);
if (argc != 4 || sizefactor < 1 || sizefactor > 100)
    printf("Usage: ./resize n infile outfile where n is 1 to 100\n");
    return 1;

// remember filenames
char* infile = argv[2];
char* outfile = argv[3];

What happens when you execute the program with no parameters? Based on what little code is listed above, it looks like you are using argv[1] to assign a value to another variable before you have verified that there are the right number of arguments.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • That's exactly what I did. Thanks! I guess I didn't realize that I couldn't assign it to a variable before checking that it exists, but it makes sense. – Brandon Terry Jul 15 '16 at 19:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .