Home > Enterprise >  Why is malloc returning a NULL pointer even though I am allocating barely 1MB of memory? [closed]
Why is malloc returning a NULL pointer even though I am allocating barely 1MB of memory? [closed]

Time:09-27

I am trying to write to a C string character-by-character but Visual Studio indicates that the pointer in question is NULL. Even though there are two functions that attempt this, only in the first one does this issue occur.

These are the two functions:

char* revstr(char* string)
{
    int len = strlen(string);
    char* retstr = (char*)malloc(30);
   // printf("%d\n", sizeof(retstr));
    int i=0, j=0;
    for (i = len, j = 0; i >=0; i--, j  )
    {
        retstr[j]=string[i]; // this generates C6011: dereferencing NULL pointer 'retstr'
                                
    }
    printf("\n");
    retstr[j] = '\0'; // also generates C6011
    printf("%s",etstr);
    printf("\n");
   
    
    return retstr;
}

char * get_name(char* string)
{
    char* retstr = (char*)malloc(30);
    int i = 0,j=0;
    for (i = strlen(string) - 1; i > 0; i--)
        if (string[i] == '.')
            break;
    while (string[i] != '/')
    {
       // printf("%c", string[i]);
     retstr[j] = string[i];
        i--; j  ;

    }
    retstr[j] = '\0';

    return retstr;
}

CodePudding user response:

C6011 is a warning, not an error. It says that you may dereference a NULL pointer.

What the compiler means is that malloc may fail, in theory with any amount, and that you are not checking that. If it were to return NULL you program will show undefined behavior.

The easiest way to avoid that, if you don't care about out of memory situations, is just add:

char* retstr = (char*)malloc(30);
if (!retstr)
    abort();

The proper way would be to return an error and propagate it upwards and handle it gracefully in the user interface layer, but that is not always so easy.

CodePudding user response:

char* retstr = (char*)malloc( something );

If you do not declare <stdlib.h> the pointer returned by malloc is autotically coerced to Integer; after that you force an integer to go to char pointer. From this second transformation it is very possible to get a NULL. Never cast the result of malloc.

  • Related