Solved

C: Deallocate Memory

Posted on 2011-03-19
11
629 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

735 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