user1255365
user1255365

Reputation:

malloc returns negative value

I am running this piece of code on a hardware.

unsigned char *buf;

buf = malloc(sizeof(int));
printf("Address of buf %d\n" , &buf);

if(!buf)
    return MEMORYALLOC_FAILURE;

The malloc is returning negative value. What could be the problem?

Upvotes: 1

Views: 2372

Answers (5)

pmg
pmg

Reputation: 108978

Type mismatch:

you try to print an address with the specifier for an int ("%d"). You should use "%p" and cast the value to void*

printf("Address of buf %p\n" , (void*)&buf);

Also note the above will not tell you where the allocated memory is. For that you'd need

printf("Address of newly allocated memory %p\n" , (void*)buf);

The cast to void* is mandated by the C99 standard (emphasis is mine)

The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

Also note that pointers to void need not have the same representation as pointers to other types.

Upvotes: 2

user7116
user7116

Reputation: 64068

You're printing the address of a memory location as a signed integer. If the memory address--for example on a 32bit machine--is more than 2,147,483,647 (0x7FFFFFFF) it will display as a negative number.

In this case you're also printing the address of a local variable on the stack rather than the address returned by malloc.

The error with using %d to print a pointer-sized value is that pointers may vary in size. The correct approach therefore would be to use the printf specifier for pointers, %p:

// nb: we don't take the address of buf,
// buf is already a pointer (thus its *value* is an address)
printf("Address of buf %p\n", buf);                                   

Upvotes: 4

Dan
Dan

Reputation: 10786

malloc returns a pointer. It never returns a negative value. If you think it is then you probably have a broken everything. On the other hand if you mean it returns a null pointer, then it means you are unable to allocate that memory.

Upvotes: 0

user1252065
user1252065

Reputation:

malloc returns either NULL (aka 0) or a memory address. Memory addresses cannot be negative. You just converted the pointer itself to a number, resulting in a negative number.

Upvotes: 1

MByD
MByD

Reputation: 137312

Address returned by malloc is not negative or positive, it just address, use %p to print it, not %d:

printf("Address of buf %p\n" , &buf);

And if you want to print the address returned from malloc, remove the ampersand:

printf("Address of buf %p\n" , buf);

Upvotes: 10

Related Questions