sean15
sean15

Reputation: 1

getting a segmentation fault even after compilation?

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

struct Result{
    int reversen;
    unsigned short count;
};

struct Result *myCount(int, int);
int main()
{
    struct Result *result;
    myCount(122333, 2);
    printf("\nReversed integer of 122333: %d", result->reversen);
    printf("\nOccurrence of 2 in 122333: %hu", result->count);  
    return 0;
}

struct Result * myCount(int n, int d)
{
    struct Result * result = (struct  Result *) malloc (sizeof (struct  Result));
    if (result == NULL)
    {
        fprintf(stderr, "\nNo storage space available\n");
        exit(0);
    }
    int rev_dig, last_dig, digit,  count = 0;
    while (n != 0)
    {
        last_dig = n % 10;
        rev_dig = rev_dig * 10 + last_dig;
        n = n / 10;
    }
    rev_dig = rev_dig * (-1);   
    result->reversen = rev_dig;

    while (n >= 1)
    {
        digit = n % 10;
        if (digit == d)
            count++;
        n = n / 10;
    }
    result->count = count;  
}

trying to reverse an integer value along with change of sign and also finding the occurrence of a digit in the number.

Basically i guess i am doing something wrong with pointers. can anyone help me out to figure out where am i going wrong?

Upvotes: 0

Views: 58

Answers (2)

Karthick
Karthick

Reputation: 1000

You are trying to access the structure pointer which was never initialized.

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

You never initialize result in main() and you never return anything from myCount().

Just do this in main()

result = myCount();

remember to check against NULL.

And in myCount()

struct Result * myCount(int n, int d)
{
    struct Result *result;
    int rev_dig;
    int last_dig;
    int digit;
    int count;

    count = 0;
    result = malloc(sizeof (struct  Result));
    if (result == NULL)
        return NULL; /* handle the error in the caller function */        
    while (n != 0)
    {
        last_dig = n % 10;
        rev_dig = rev_dig * 10 + last_dig;
        n = n / 10;
    }
    rev_dig = rev_dig * (-1);   
    result->reversen = rev_dig;    
    while (n >= 1)
    {
        digit = n % 10;
        if (digit == d)
            count++;
        n = n / 10;
    }
    result->count = count;
    return result;
}

Fixes:

  1. Return NULL if malloc() fails, imitating the behavior of malloc(). Functions that return pointers to newly allocated memory usually do this, e.g. strdup().

  2. Removed the superflous cast of malloc().

  3. Returned result at some point.

Not returning a value from a function declared as returning something is undefined behavior.

Upvotes: 4

Related Questions