-4

I am trying to convert and store an integer into a char pointer. So far this is what I have.

char * str1;
sprintf(str1,"%d",10);

I keep getting a Segmentation fault error.

If the code below works then why doesn't the above?

char * str1;
str1 = "Hello World";
printf("%s\n", str1);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
olfek
  • 3,210
  • 4
  • 33
  • 49

3 Answers3

1

Declaring char *str doesn't create a piece of memory. It simply states that you have a pointer with type char * and the identifier str.

Stack allocation

beware theres limited stack space and you can't return str from a function where statically allocated

char str[10];
sprintf(str1,"%d",10);

Heap allocation

beware, to avoid memory leaks, free has to be called after you're done with the string.

#include <stdlib.h>

...
char *str = malloc(10);
sprintf(str1,"%d",10);
...
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
Work of Artiz
  • 1,085
  • 7
  • 16
0

In the first case, before you can use

 sprintf(str1,"%d",10);

you need to allocate memory for str1. Otherwise, you'll end up using uninitialized memory which may point to invalid memory location which in turn invokes undefined behavior.

Considering an array, like

char str1[32] = {0};
snprintf(str1, 31, "%d",10);

can do the job for you.

In the second case, str1 is not uninitialized, it points to the starting of the string literal, so the access is valid.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

It's ovious there was no memory to store the chars

char * str1 = malloc(sizeof(char)*10); //#include <stdlib.h> for malloc to allocate memory for keeping the chars
sprintf(str1,"%d",10);

May be you are new to c language, use char array instead of pointer to avoid confusion.

char str1[10]; // this will allocate memory while defination
sprintf(str1,"%d",10);

Two methods are quiet different but in this problem any can be used

Sudip Bhattarai
  • 1,082
  • 9
  • 23