previouslyactualname
previouslyactualname

Reputation: 713

Segmentation fault in GCC

I am new to C and am trying to figure out pointers. I tried this simple(according to me) code and keep getting a segmentation fault in GCC

#include<stdio.h>
int main()
{
    char c[50] = "abc";
    char h[50];

    char *ptr;
    printf("abc");
    ptr = c;

    printf("Address stored in ptr: %p" , ptr);

    printf("Value of ptr: %s" , *ptr);
}

I read up on segfaults and found that they occur when i try to reference memory that does not belong to me. Where am I doing this in this code? Thanks!

Upvotes: 0

Views: 512

Answers (2)

Hristo Iliev
Hristo Iliev

Reputation: 74355

printf("Value of ptr: %s" , *ptr); tells the computer to interpret the value stored at the address pointed to by ptr as the address of a string. In most cases that would be the address of an unmapped memory region (0x636261 on little-endian machines, e.g. x86 / x64) and therefore the segmentation fault.

Since the %s format specifier expets the address of a string, it is not necessary to dereference the pointer:

printf("Value of ptr: %s" , ptr);

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

Change this statement

printf("Value of ptr: %s" , *ptr);

to either

printf("Value of ptr: %c" , *ptr);

or

printf("Value of ptr: %s" , ptr);

depending on what you want to see. Or use them both that to see the difference.:)

Upvotes: 4

Related Questions