Re: Access violation in free()



spl wrote:
I am getting access violation in the below program for the free()
call, Whats wrong here and how to rectify it?

Try the following and see if you have better luck:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#if 0
#include <conio.h>
#endif

char *CopyString(char *s)
{
int length = strlen(s);
char *t = malloc(length+1); /* note! */
strcpy(t, s); /* in your original code, this violated the bounds of the array pointed to by t, corrupting memory. */
return t;
}

#if 0
void main()
#endif
int main(void)
{
char *destStr;
char *sourceStr = "Test";
destStr = CopyString(sourceStr);
printf("Destination String : %s\n", destStr);
free(destStr);
return 0;
}


----------------------------------
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>

char * CopyString(char *s)
{
int length = strlen(s);
char * t = (char *)malloc(length);
strcpy(t,s);
return t;
}


void main()
{
char *destStr;
char *sourceStr = "Test";
destStr = CopyString(sourceStr);
printf("Destination String : %s\n", destStr);
free(destStr);

}

.



Relevant Pages