Question

I want to cast int to char. This is my code.

#include <stdio.h>
int main(){
        int i = 7;
        char *s;
        sprintf(s,"sprint f = %d",i);
        printf("printf s = [%s]",s); 
} 

It ends Segmentation fault. What’s wrong is it?

Was it helpful?

Solution

You do not have any memory allocated for s. It's just a pointer that is either NULL or pointing to a random location (depending on the compiler). Trying to write to it is like going to bed without caring where you are - and the probability that you've just broken into someone else's house is way larger than randomly selecting your own bed. Thus, Segmentation Fault - the computer's way of getting your program arrested.

To allocate the memory, you can either let the compiler set some aside for you (char s[22]), or allocate your own (char *s = malloc(22)).

OTHER TIPS

s is an invalid pointer - therefore you can't write to the memory it points to (if any), nor can you read from it. Allocate memory for it:

char s[64];

or

char* s = malloc(64);

Code needs memory to sprintf() the data.

With some embedded apps, I need to be lean, yet tolerant of int as 16, 32 or potentially 64 bit, so to right-size the buffer:

static const char *format[] = "sprint f = %d";

// Size `s` to be sufficiently large as format and int size may change.
char s[sizeof format + sizeof(int)*3 + 3];

sprintf(s, format, i);
printf("printf s = [%s]",s); 

I like using the sizeof(some_integer_type)*3 + 3 to account for the memory needed for all sorts on integer types.

(Note: Cheating as I assume CHAR_BIT == 8)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top