Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test to see if I should free memory or not

Tags:

c

pointers

I am passing a pointer to a char array to my method, as well as a value for the actual height of the char array. I am looping through to see if all values are 0, if they are then return 0, else return 1.

The method is used as a test to see if I should free memory or not and set the pointer to null if it is full of 0's. The issue i am having is that the program should have "some unfree" memory at the end, so I have no idea whether or not its doing it correctly - and gdb I struggle with immensely.

Thanks for reading

int shouldBeNull(char *charPointer, int sizeOfCharArray)
{
    int isIn = 0;
    int i = 0;

    while(i < sizeOfCharArray){
        if(*charPointer != '0'){
            isIn = 1;
            break;
        }
        i++;
        charPointer++;
    }   
    return isIn;     
}
like image 378
sbsp Avatar asked Mar 24 '10 18:03

sbsp


2 Answers

When you say "...all values are zero...", I was assuming that you meant binary values of zero, rather than the character '0'...

if(*charPointer != '0'){

This is the zero-digit character (ASCII 0x31) rather than a NUL character (ASCII 0x00). If you were trying to check for zero bytes, try the following:

if (*charPointer != '\0') {

Also, you're not incrementing or offsetting your character pointer charPointer, so you're always testing the first character.

if (*charPointer++ != '\0) {

...or...

if (*(charPointer + i) != '\0) {
like image 76
Scott Smith Avatar answered Oct 03 '22 01:10

Scott Smith


You are not incrementing charPointer

like image 40
Adil Avatar answered Oct 03 '22 00:10

Adil