Solved

C: Deallocate Memory

Posted on 2011-03-19
11
625 Views
Last Modified: 2012-06-22
I'm trying to deallocate memory by deleting the array but I am getting the attached error message.

 
#include <stdio.h>
#include <stdlib.h>
/* declare global var's */

int hamming_length=0, parity_type=-1;

/* declare & initialize hamming string */

char *hamming = NULL;

/* Option #1 */

void params() {
	printf("Enter the length of the Hamming code: ");
	scanf("%d", &hamming_length);
	printf("Enter the parity (o=even, 1=odd): ");
	scanf("%d", &parity_type);

	hamming = (char *) malloc (hamming_length * sizeof(char));
}

/* Option #2 */

void check_hamming_code() {
	/* declare local var's */
	
	int i,j,k, error_bit=0;

	/* prompt for hamming code string */
	printf("Enter the Hamming code: ");
	scanf("%s",hamming);

	for(i=1; i < hamming_length; i*=2) {
		int current_parity = parity_type;

		for(j=i; j <= hamming_length; j+=2*i) {

			for(k=j; (k <= hamming_length) && (k < i+j); k++) {
				
				if(k != i) 
					current_parity = current_parity ^ (hamming[hamming_length-k]-'0');
			} /* end of k loop */
		} /* end of j loop */
		error_bit = error_bit + (current_parity ^ (hamming[hamming_length-i]-'0'))*i;
	} /* end i loop */

	/* correct error bit */

	if(error_bit == 0)
		printf("There is no bit error\n");
	else {
	printf("There is an error in bit: %d\n",error_bit);

	if((hamming[hamming_length - error_bit]-'0') == 0) {
		hamming[hamming_length - error_bit] =  (hamming[hamming_length-error_bit] +1);
	}
	else {
		hamming[hamming_length - error_bit] =  (hamming[hamming_length-error_bit] -1);
	}
	printf("The corrected Hamming code is: %s\n", hamming);
	}
}

/* Option #3 */

void exit_program() {

	if(hamming != NULL)
		free(hamming);
}

int main() {
	/* declare local var's */

	int menu_option = 0;

	while(menu_option != 3) {
		printf("\n");
		printf("Error detection/correction:\n");
		printf("------------------------------------\n");
		printf("1) Enter parameters\n");
		printf("2) Check Hamming code\n");
		printf("3) Exit\n");
		printf("\n");
		printf("Enter selection: ");
		scanf("%d",&menu_option);
		printf("\n");

		switch (menu_option) {
		case 1: params(); break;
		case 2: check_hamming_code(); break;
		case 3: exit_program(); break;
		default: break;
		} /* exit switch statement*/
	} /* exit while statement*/
	return 0;
}

Open in new window

1.png
0
Comment
Question by:InfoTechEE
  • 4
  • 4
  • 3
11 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 250 total points
ID: 35173205
You need to take the terminating NULL byte into account when allocating memory for the string, otherwise this addtional byte will cause that overwrite - just make that
void params() {
	printf("Enter the length of the Hamming code: ");
	scanf("%d", &hamming_length);
	printf("Enter the parity (o=even, 1=odd): ");
	scanf("%d", &parity_type);

	hamming = (char *) malloc ((hamming_length + 1) * sizeof(char)); // <------------- !
}

Open in new window

0
 
LVL 32

Assisted Solution

by:phoffric
phoffric earned 250 total points
ID: 35173212
Did you enter a length, n, and then enter n chars using a scanf? If so, then the scanf made a c-style string out of your entry by adding on a terminating null byte. In that case you needed n+1 bytes allocated for the n chars. So, maybe you should have malloc'd n+1 bytes instead of n.

Also, even you said the length was n, and you accidentally type in n + 5 chars, then you will still overflow the malloc'd region. So the quick answer is to malloc n + 100 to handle misuse at the keyboard.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 35173218
Hmm, my email must be slow today.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 35173240
Now better than scanf is getline (since you specify the C++ zone).
    http://www.cplusplus.com/reference/iostream/istream/getline/
Now you can specify the max number of chars to read and avoid overflowing your buffer.

Or, in C, fgets using standard input:
    http://www.cplusplus.com/reference/clibrary/cstdio/fgets/
0
 

Author Comment

by:InfoTechEE
ID: 35173320
Thanks to the both of you. Now that I understand where the problem is, I still don't understand why it is a problem.

Yes the user does specifies length, and provides the string.
hamming_length = 7
hamming = 1000110

Array Initialized:
[ ] [ ] [ ] [ ] [ ] [ ] [ ]

Array populated:
[ 1 ] [ 0 ] [ 0 ] [ 0 ] [ 1 ] [ 1 ] [ 0 ]

So in my environment where I'm NOT specifying hamming_lengh + 1, whats happening to my Terminating NULL?

Either way, even though I have an array of 7 elements, plus a terminating NULL why can I not deallocate it?
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 86

Expert Comment

by:jkr
ID: 35173326
>>So in my environment where I'm NOT specifying hamming_lengh + 1, whats
>>happening to my Terminating NULL?

Since you are allocating one byte less, this terminating NULL is overwriting the heap, thu causing the error message you were experiencing.
0
 

Author Comment

by:InfoTechEE
ID: 35173335
So is my Array 7 characters, or does the terminating NULL implicitly add an element making it 8 characters long?
0
 
LVL 86

Expert Comment

by:jkr
ID: 35173340
Yes, that's exactly what is happening. You always have to take the terminator into account seperately when allocating memory for a string in C/C++. 'malloc()' does not know what teh memory is being used for, so you have to take care yourself.
0
 

Author Comment

by:InfoTechEE
ID: 35173345
OK, I understand that part completely. So now I have an arrray of 8 characters, even though the user said only 7. Why can I not deallocate it all by using free(array)?

Logically I think I should be able to. Just because the NULL implicitly adds an element to my array.
0
 
LVL 86

Expert Comment

by:jkr
ID: 35173355
>>Why can I not deallocate it all by using free(array)?

That should work just fine - at least it does here...
0
 
LVL 32

Expert Comment

by:phoffric
ID: 35173466
Working with VS 2010 Express, I got your error in your OP. When I added 1 to the malloc to account for the null byte, the problem went away.

When you go write outside of an allocated region, you may be writing into a byte that no one is using or will be used, in which case you may see no ill effects.

Or, you  may be writing over a piece of memory that is in use. Perhaps it is being used by memory management. From one run to the next, with just a small amount of code changes, the results can run from benign to a problem. As the memory layout is changed, the behavior of incorrect code changes.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now