0

I have these three files main.h, 4-main.c and 4-print_rev.c and all three are required to print a string in reverse. I am not permitted to use standard libs, hence the reason for not using strlen() or printf() and I have to use _putchar() which performs same actions of putchar()

However, when I compile and run on my Linux sandbox, I get segmentation fault (core dumped) error. I used an online compiler and it worked just as it should. Please help.enter image description here

main.h

#define MAIN_H

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

int _putchar(char c);
void reset_to_98(int *n);
void swap_int( int *a, int *b);
int _strlen(char *s);
void _puts(char *s);
void print_rev(char *s);

#endif

4-main.c

#include "main.h"

/**
 * main - check the code
 *
 * Return: Always 0.
 */
int main(void)
{
    char *str;

    str = "I do not fear computers. I fear the lack of them - Isaac Asimov";
    print_rev(str);
    return (0);
}

4-print_rev.c

#include "main.h"

/**
 * print_rev - prints a string
 * @s: the string to be printed
 */

void print_rev(char *s)
{
        int i;

        while (s[i] != '\0')
        {
                i++;
        }
        while (i > 0)
        {
                _putchar(s[i-1]);
                i--;
        }
        _putchar('\n');
}
1
  • 3
    The variable i in print_rev is not initialized int i;. It seems you mean int i = 0; Commented Feb 27, 2023 at 22:16

1 Answer 1

0

I realized that not initializing my iterator i to 0 was the cause of the segmentation fault.

So I updated my 4-print_rev.c to this and I am good to go. Thanks again @Vlad

#include "main.h"

/**
 * print_rev - prints a string
 * @s: the string to be printed
 */

void print_rev(char *s)
{
        int i = 0;

        while (s[i] != '\0')
        {
                i++;
        }
        while (i > 0)
        {
                _putchar(s[i-1]);
                i--;
        }
        _putchar('\n');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.