TheBlueCat
TheBlueCat

Reputation: 1195

Pointers in C with Segmentation fault (core dumped) error

I was just trying to test if I installed a new ide correctly and tried to compile this basic program, both in the IDE and with gedit and GCC and it would compile, but crash after I launch the executable in the command line - I have no idea what's wrong, as I'm still fairly new to pointers in C and it takes a while to wrap your head around the theory, according to most people.

Code:

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

    char print_func(char *hi);

    int main(void) {
        char *hi = "Hello, World!";
        print_func(*hi);
    }

    char print_func(char *hi) {
        printf("%d \n", *hi);
    }

I tried this:

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

char print_func(char *hi);

int main(void) {
    char *hi = "Hello, World!";
    print_func(&hi);
}

char print_func(char *hi) {
    printf("%d \n", *hi);
}

and it outputs 44 with no crash.

Upvotes: 0

Views: 4541

Answers (4)

Yogeesh Seralathan
Yogeesh Seralathan

Reputation: 1424

That's because you are passing a character value to the function and giving that as the address to the pointer variable "hi" in print_func. If your program was aimed at printing the string then this would be good -->

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

char print_func(char *hi);

int main(void) {
    char *hi = "Hello, World!";
    print_func(hi);
}

char print_func(char *hi) {
    printf("%s \n", hi);
}

Upvotes: 1

perreal
perreal

Reputation: 98118

If you do indirection using, print_func(*hi); you are passing a char and it is one byte. So when you are trying to read an integer, which is larger, an access violation occurs. You should call your function with a pointer print_func(hi). And if you want to print the address of a string, it is better to use %p in printf:

printf("%p \n", hi); // print the address of hi

If you want to print the first character in hi, use %c instead:

printf("%c \n", *hi); // print first character of hi

If you want to print the value of the first character in hi, use %d instead, with casting:

printf("%d \n", (int)*hi); // print the value of the first character of hi

To print the whole string use %s and pass the pointer:

printf("%s \n", hi);

Upvotes: 1

md5
md5

Reputation: 23737

Well, your function is waiting a string as parameter, and you send a character or a pointer to string !

If you want to print the first character of the string, you should just send your string.

print_func(hi);

Upvotes: 0

Mahesh
Mahesh

Reputation: 34655

Even in the second case, I see a problem.

print_func(&hi);

You are passing the address of the pointer while you have to pass just pointer itself. Drop the & in function call.

Upvotes: 0

Related Questions