1

In pset4 I want to create randomly colored bricks. To that end I created a function that returns a hex string. When I run it I get a segfault. Using gdb I have narrowed down the issue to the below snippet:

string color = "";
int c = (int) (rand() % 256);
sprintf(color, "%x", c);

The segfault is happening on the call to sprintf.

How can I convert from an int to a hex string??

3

You're initializing the string color with a string literal. This is stored in a read-only memory — you can't modify its contents.

To be able to modify the contents of a string, here are 2 approaches

Approach #1:

to declare an array of chars that's big enough to hold the characters of the string + the null character

char color[7];

Approach #2:

to allocate enough memory on the heap to hold the characters of the string + the null character

string color = malloc(7 * sizeof(char));

If you chose the second approach, keep in mind that you should free the string after you finish using it by calling free(). Both malloc and free are declared in stdlib.h. So you'll also need to include it.

1
  • Thanks Kareem. I used the first approach, it worked perfectly!
    – Lefko
    Sep 16 '14 at 10:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .