• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 638
  • Last Modified:

C: Deallocate Memory

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
InfoTechEE
Asked:
InfoTechEE
  • 4
  • 4
  • 3
2 Solutions
 
jkrCommented:
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
 
phoffricCommented:
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
 
phoffricCommented:
Hmm, my email must be slow today.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
phoffricCommented:
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
 
InfoTechEEAuthor Commented:
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
 
jkrCommented:
>>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
 
InfoTechEEAuthor Commented:
So is my Array 7 characters, or does the terminating NULL implicitly add an element making it 8 characters long?
0
 
jkrCommented:
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
 
InfoTechEEAuthor Commented:
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
 
jkrCommented:
>>Why can I not deallocate it all by using free(array)?

That should work just fine - at least it does here...
0
 
phoffricCommented:
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!

  • 4
  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now