1

I'm trying to convert an int to a char*. I'm on a Mac OS X so I can't use itoa, since it's non-standard, I'm trying to use sprintf or snprintf but I keep on getting segmentation fault: 11. Here's what I've got:

snprintf(msg, sizeof(char *), "%d", 1);

So I'm hoping for a suggestion, what can I do?

C. Porto
  • 631
  • 3
  • 12
  • 26

2 Answers2

1

It's likely that msg, which is a char *, doesn't point to memory that it can use. So you first have to dynamically allocate memory that will be used to store the string.

msg = malloc(12); // 12 is an arbitrary value
snprintf(msg, 12, "%d", 1); // second parametre is max size of string made by function

Alternatively, you can instead declare a static buffer. That way, you won't have to free any memory.

char msg[12]; // again, 12 is an arbitrary value
snprintf(msg, sizeof(msg), "%d", 1);
AntonH
  • 6,359
  • 2
  • 30
  • 40
0

How do you declare msg?

Something like this should work:

char msg[15];
snprintf(msg, sizeof(msg), "%d", 1);

Note that the second argument to snprintf is the length of the string, not the size of a character.

user3553031
  • 5,990
  • 1
  • 20
  • 40