0

I'm new to programming and I'm stuck on this program which converts Celsius to Fahrenheit. Please help me figure out the problem with my code:

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, string argv[])
{
    float celsius = atof(argv[1]);
    if (argc != 2)
    {
        printf("Usage: ./fahrenheit <celsius temp>\n");
        return 1;
    }

    float fahrenheit = (celsius * 9) / 5 + 32;
    printf("F: %.1f\n", fahrenheit);

}

When I don't pass any argument to the program I get the following error message:

fahrenheit.c:8:26: runtime error: null pointer passed as argument 1, which is declared to never be null

/usr/include/stdlib.h:145:33: note: nonnull attribute specified here

Segmentation fault

Thanks!

0

The segmentation fault comes from the following line:

float celsius = atof(argv[1]);

because we are trying to access a memory address that we should not access (surely NULL), the solution is as simple as changing the order of things, first check that we have two arguments and then convert the second argument to double:

  if (argc != 2)
    {
        printf("Usage: ./fahrenheit <celsius temp>\n");
        return 1;
    }

float celsius = atof(argv[1]);
0

The code is trying to access argv[1] and assign its contents to celsius before verifying that argc == 2. Since argv[1] doesn't exist when no parameter is given, it generates a seg fault.

The problem is simply a matter of the order of the first two lines of code inside of main.

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

You must log in to answer this question.

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