Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why can't I return NULL?

I’m a beginner trying to learn dynamic memory allocation in c.

I’m trying to return NULL if text doesn’t have anything in it, if it has something in it I want to return the text.

char* check_for_NULL(const char *text){
    if(text == NULL){
        return NULL;
    }
...
}

(the rest of the program works as intended)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I put NULL where I call it:

int main(){
char *check_NULL;

    check_NULL = check_for_NULL(NULL);
    printf("%s", check_NULL);
    free(check_NULL);

}

I get segmentation fault instead of null.

when I run in valgrind I get the result:

Invalid read of size 1

Address 0x0 is not stack'd malloc'd or (recently) free'd

tried to make space for NULL with calloc, tried to put 0 instead of NULL but nothing works

saw a similar post:

Valgrind: Invalid read of size 1

but didn’t get what the fix was.

>Solution :

If the pointer check_NULL is equal to NULL then this statement

printf("%s", check_NULL);

invokes undefined behavior.

At least you should write

if ( check_NULL != NULL ) printf("%s", check_NULL);

Pay attention to that to make this statement correct

free(check_NULL)

the function should return either a null pointer or a pointer to a dynamically allocated memory.

Pay attention to that the phrase

text doesn’t have anything in it,

means that an empty string is passed to the function. To check whether a string is empty you should write for example

if ( text[0] == '\0' )
//...

or

if ( !*text )
//...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading