Emman
Emman

Reputation: 1244

Printing char* resulting in segmentation fault?

The following program results in segmentation fault [I have used gcc as compiler], How to print str in the character pointer and why segmentation fault?

#include <stdio.h>
#define LOW 0x40000000
#define HIGH 0x0

int main()
{
 volatile char* str = (char*) (HIGH + LOW);
 printf ( "Character Str:%s",str);  
}

Upvotes: 0

Views: 1807

Answers (1)

Grant Sanders
Grant Sanders

Reputation: 337

You are assigning the pointer str to point to an absolute memory address, memory address 0x40000000. The (char*) cast is why your compiler isn't complaining. There is almost certainly nothing useful at that address because you haven't declared anything besides that pointer. Don't use absolute memory addressing unless you're writing an operating system or are coding for a legacy system without virtual memory for each program. Even then it's a bad idea if you don't know what you're doing.

printf is failing because you're telling it look for a valid string starting at the memory pointed to by ptr and print it out to stdout (e.g. your console). In the highly unlikely event that address 0x40000000 is readable by your process at the time of execution and it contains a valid, null-terminated string, it would print something out without the segfault. It would still be gibberish.

Based on the number you chose for HIGH, it looks like you were trying to null-terminate a string. If you wanted to create a string that printf could print you might try something like this:

char str[12] = "Hello World";
printf ( "Character Str:%s",str);

Once that was properly allocated, you could could create a pointer and work with that if you so desired.

char *strptr = str;
printf ( "Character StrPtr:%s",strptr);

I may be way off base on what you were actually trying to do. But what you are doing is not valid, and what you are trying to do is not obvious.

Upvotes: 1

Related Questions