0

I have an integer array that is dynamically allocated by the following:

int *ranArr(int size) {
    int *arr= malloc(size *sizeof(int));

    for(int i = 0; i < size; i++) {
        arr[i] = genRan(size);
    }

    return arr;
}

I want to dynamically allocate memory for a string that I will convert my integer array into and store it in the string:

        int *arrayCopy = ranArr(size);
        int arrayCopyLen = size;
        char *arrayString= (char*) malloc(size * sizeof(char));
        int index = 0;
        for(int i = 0; i< arrayCopyLen ; i++) {
            index += sprintf(&arrayString[index], "%d ,", arrayCopy[i]);
        }
        int arrayStringLen = strlen(arrayString)+1;

This works for array sizes around 1000 but when I set the size to 2000 or so it breaks and I get a segmentation fault.

6
  • What is arrString? it's not defined in your code Commented Jun 12, 2018 at 16:33
  • What's genRan? Commented Jun 12, 2018 at 16:34
  • @EugeneSh. This function takes an integer as parameter (typeof size) and returns an integer (typeof arr[i]). This function calculates something that is unimportant for the problem. The function name suggests some random number generation, but that's a guess. Commented Jun 12, 2018 at 16:45
  • @harper that is correct, it just generates a random number from 0 to size. Commented Jun 12, 2018 at 17:13
  • @ChrisTurner just made a type, corrected it in the edit! Commented Jun 12, 2018 at 17:13

1 Answer 1

3

You're not allocating enough memory for your string.

Converting a single int to a string takes up up to 12 bytes, assuming an int is 32 bit. For example, converting the value -2000000000 to a string needs 12 characters. So you need at least 12 * size bytes for your string, plus room for the ", " characters and the null terminator.

Also, sizeof(char) is 1 by definition, so no need to multiply by that.

char *arrayString = malloc(size * 14 + 1);   
// 14 = 12 bytes for a 32-bit int plus 2 bytes for ", "
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.