0

I have allocated memory for a char pointer in this code and I wanted check does it points anything:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char *p  = (char*) malloc(sizeof(char)*10);
    if(*p == 0)
       printf("The pointer points nothing !\n");

}

And I checked that if it doesn't point anything. Also I print of pointer's length and it prints "3" although it prints nothing. What is reason of this and how can I check if it points nothing ?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
okydoky
  • 31
  • 1
  • 7
  • The space allocated by malloc is uninitialized. It's not possible to check whether or not something is uninitialized. You should store values there before reading them back – M.M Nov 20 '18 at 08:59
  • I don't see the code where you *'print of pointer's length and it prints "3"'* - did that somehow get lost while you were posting? – Toby Speight Nov 20 '18 at 09:11
  • Sorry, i have forgotten to add this. – okydoky Nov 20 '18 at 09:22

1 Answers1

3

You need to modify the check to check against the returned pointer, not the content. Something like

if( p == NULL) {
    fprintf(stderr, "The pointer points nothing !\n");
    return 1;
 }

should do. Quoting the standard regarding the return values:

The malloc function returns either a null pointer or a pointer to the allocated space.

The null pointer is returned in case of a failure, otherwise the pointer returned should be non-equal to a null pointer.

That said,

  • The initial content of the pointed memory is indeterminate, do not attempt to verify it. Quoting from the standard,

    The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

    That goes for your other question regarding "checking the length" of the pointer - it's pointless. Unless you have stored (write) some value into it - there's no point trying to measure the initial content, as it is indeterminate. You may eventually run into undefined behavior.

  • The cast for the returned pointer by malloc() and family is superfluous. It can be totally avoided in C.

  • sizeof(char) is guaranteed to be 1, in C. Thus, using sizeof(char) as a multiplier, is again not needed, per se.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261