I have been stuck on this one for a while, I’m not an expert in C. Basically, I am trying to make a function that “safely” strcats a character to an existing char *.
I am trying to get the “dynamic allocation” method working from this example:
I have made a few modifications, I removed the var that’s set by the realloc function (the compiler said that it returned void). I also modified it to only append one character instead of an array of characters. I figured this would change the “realloc” parameters, so instead of passing the length of the addition string, I just passed in “sizeof(char)” (x2 because the original had an extra sizeof char, i think because of the null terminator?)
char *buffer = NULL;
int mystrcat(char addition)
{
realloc(buffer, strlen(buffer) + sizeof(char)*2);
if (!buffer)
return 0;
strcat(buffer, addition);
return 1;
}
I call it like this:
if(!safestrcat(str[i+j]))
printf("Out of Memory");
For some reason, I am seeing this:
Unhandled exception at 0x60f0d540 (msvcr100d.dll) in myProg.exe:
0xC0000005: Access violation reading location 0x00000000.
And the debugger shows me strlen.asm at line 81:
main_loop:
mov eax,dword ptr [ecx] ; read 4 bytes
I’m sorry if this is a newb question, but what is happening? Why is the addition char not being appending to the buffer?
Sorry I should add, that it compiles succesfully.
sizeof(char)is 1 by definitionrealloccode is brokenstrcatdoesn’t take acharas its second argumentstrcatdoesHowever, pay attention to two things:
mystrcatwith a valid, initialised pointer – same asstrcat!In the case of failure, the function returns
NULL– in that case, it’s the caller’s responsibility to ensure that the original buffer’s memory is freed. This means that you mustn’t call the function as– This may cause a memory leak.
So a correct usage would be:
Yes, convoluted. This is the price for safe memory operations.