Sam Schmalzried Sam Schmalzried - 1 year ago 218
C Question

C - Segmentation Fault (core dumped)

I am trying to write a simple C program that takes the input of a number and returns the sum of the number's digits as well as the reverse of the number. The program is currently incomplete because I keep encountering Segmentation Fault errors when testing it.

Here is the code:

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

int sumdigits(int);

int main() {
int num; // The number to be read
int reverse; // The reverse of the input
int sum; // The sum of the digits

printf("Enter a number: ");
scanf("%d", &num);
sum = sumdigits(num);
printf("Sum of digits: %s", sum);

int sumdigits(int number) {
int sum = 0;
int temp = number;
while (temp != 0) {
sum += (temp % 10);
temp /= 10;
return sum;

By using some print statements, I've discovered that the error most likely occurs somewhere in these lines:

printf("Enter a number: ");
scanf("%d", &num);

I am able to enter a number, but immediately after that I get a message saying Segmentation Fault (core dumped) and the program exits. Running the program with sudo privileges just provides Segmentation Fault, without the "core dumped" part of the message.

Debug info provided by instructions followed here seems to indicate that the printf statement is what is causing the error, as this is the output:

(gdb) run
Starting program: /home/sschmalz/Documents/Classes/CIS308/proj1/debug
Enter a number: 123

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a62fb4 in vfprintf () from /lib64/

However, I don't know what to do with this information, so I can't resolve the error.

I have asked my professor for help with this same error in lab, and he was unable to find a solution. This has happened in two different labs now, plus with this project, which makes me think that it may be something with my computer's setup rather than with the code itself.

I am writing the program using vim and compiling using gcc. In most cases I am not renaming the output of the compiler, so I am running it using "./a.out" I am using Fedora 24 to write and run these programs. If any other information about my system is needed, please let me know.

Answer Source


printf("Sum of digits: %s", sum);


printf("Sum of digits: %d", sum);

%s is for strings not for integers (%d is for signed integers).


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download