Search code examples
cpointersnulldynamic-memory-allocation

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)

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 )
    //...