memory leaks

Aug 10, 2011 at 12:38pm
Hi,
I'm having some problems with memory leaks and can't figure out how to fix the problem.
the code below is used to change letters in a string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string.h>
#include <stdlib.h>
char *abc(char *string){
..... <-Just some declarations
char *encode = new char;
strsize = strlen(xxx);
enc = (char*) malloc (strsize);
for(int n=0;n<strsize;n++){
    ....<-process in which a new char is being change in string
    enc[n]=newchar;
}
encode[strsize]='\0';
return encode;
}


1
2
3
4
5
void main(){
	char *newstring;
	newstring = abc("Hello");
	delete newstring;
}

The code compiles fine.
The problems is that when the code reaches the delete command i get an error.
"Heap Corruption Detected"
"CRT detected that the application wrote to memory after end of heap buffer."
I have no clue how to solve this problem.
Any help is appreciated.
Thanks,
phoenix1990
Aug 10, 2011 at 12:51pm
A couple of things: You shouldn't mix malloc and delete: Either use new/delete or malloc/free.
Second thing is add one to strsize when you allocate your string for the null byte. Remember, arrays are zero-based, so your valid indices are 0 to strsize - 1.
Aug 10, 2011 at 1:10pm
char *encode = new char;

encode is a pointer that points to enough space for a single character.

encode[strsize]='\0';

Is strsize is anything other than zero, you're writing over memory that isn't yours, because encode points to enough memory for one char only.

If you're going to code in C++, don't use these C-style strings if you can aviod it. Use proper C++ string objects.
Last edited on Aug 10, 2011 at 1:11pm
Aug 10, 2011 at 1:32pm

You shouldn't mix malloc and delete: Either use new/delete or malloc/free.

Is strsize is anything other than zero, you're writing over memory that isn't yours, because encode points to enough memory for one char only.

Thanks for the help kooth and Moschops.
Your comments really help me to resolve all the issues i was having with the code.
Now everything works perfectly.
Thankyou guys.
Topic archived. No new replies allowed.