flexzican
flexzican

Reputation: 97

Appending Char array to Char pointer

I have been on this fow quite some time now and i dont seem to figure it out.

I have this code:

    unsigned char *src;
    int length = (parameterArray[i].sizeInBits/8) + 1; // check how long array should be
    unsigned char tmp[length]; // declare array

    memcpy(tmp, (char*)&parameterArray[i].valueU8, length); // in this case copy char to array
    src = realloc(src, strlen(src) + strlen(tmp)); // reallocate space for total string
    strncat(src, tmp, strlen(tmp)); // merge 

every time the code crashes on the reallocating part.

I have tried almost everything and nothing works. Please help

Upvotes: 0

Views: 2050

Answers (3)

hmjd
hmjd

Reputation: 121961

src is an unitialized pointer, and will hold a random memory address. The preconditions for realloc() state. from the linked reference page:

Reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed with free(), otherwise, the results are undefined.

When using realloc() store the result to a temporary variable to avoid a memory leak in the event of failure.

Additionally, calling strlen() on src will also result in undefined behaviour. As first pointed out by mani tmp must be null terminated in order for strlen() and strcpy() to work correctly. The space calculated in the realloc() must be increased by one to allocate an additional char for the terminating null character.

Example code fix:

unsigned char tmp[length + 1];
memcpy(tmp, parameterArray[i].valueU8, length);
tmp[length] = 0;

unsigned char* src = NULL;
unsigned char* src_tmp = realloc(src, (src ? strlen(src) : 0) + strlen(tmp) + 1);
if (src_tmp)
{
    if (!src) *src_tmp = 0; /* Ensure null character present before strcat(). */
    src = src_tmp;
    strcat(src, tmp);
}

Upvotes: 4

Mani
Mani

Reputation: 17585

As per your code of this line memcpy(tmp, (char*)&parameterArray[i].valueU8, length); you are trying to copy valueU8 which must be assigned with Null terminator. Otherwise it will crash in this line src = realloc(src, strlen(src) + strlen(tmp));

Upvotes: 2

Ahsan
Ahsan

Reputation: 1

From man pages of realloc

Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().

and your src is an uninitialized pointer

Upvotes: 0

Related Questions