Re: Access violation in free()
- From: Martin Ambuhl <mambuhl@xxxxxxxxxxxxx>
- Date: Sat, 01 Sep 2007 19:40:00 -0400
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);
}
- Follow-Ups:
- Re: Access violation in free()
- From: Richard Heathfield
- Re: Access violation in free()
- References:
- Access violation in free()
- From: spl
- Access violation in free()
- Prev by Date: Re: Access violation in free()
- Next by Date: Re: Access violation in free()
- Previous by thread: Re: Access violation in free()
- Next by thread: Re: Access violation in free()
- Index(es):
Relevant Pages
|