C Programming - Memory Allocation - Discussion

Discussion Forum : Memory Allocation - Point Out Errors (Q.No. 2)
2.
Point out the error in the following program.
#include<stdio.h>
#include<stdlib.h>

int main()
{
    char *ptr;
    *ptr = (char)malloc(30);
    strcpy(ptr, "RAM");
    printf("%s", ptr);
    free(ptr);
    return 0;
}
Error: in strcpy() statement.
Error: in *ptr = (char)malloc(30);
Error: in free(ptr);
No error
Answer: Option
Explanation:
Answer: ptr = (char*)malloc(30);
Discussion:
10 comments Page 1 of 1.

Zaddy said:   8 years ago
@Cherry.

It's right.

Vishu said:   8 years ago
@All.

ptr is a char ptr which does not hold any address it's a const ptr so when we allocate memory with ie, ptr =(char *) malloc(30); after it stores the RAM in it. bt when we use lik dis i,e *ptr = (char ) malloc (30); its a segmentation fault(core dumped).

Because first of all its typecasting is wrong and second one is ptr is already pointer bt again they use ptr as *ptr. so for correct answer we must use ptr = (char *)malloc (30);.

If I made any mistake correct me. Thank you.

Cherry said:   1 decade ago
What about strcpy(ptr, "RAM");?

ptr stores the address? Is this statement right or not?

Swapnil patel said:   1 decade ago
malloc return value is void *, when write only (char)malloc(); then get error or segmentation fault but, write (char*) malloc();

Then write proper value RAM.

Suhail k k said:   1 decade ago
malloc return void type and so we have to type cast into type of the LHS. ptr is the pointer to the char type. So we should use char*.

TSK said:   1 decade ago
It's a wild pointer. Because, ptr is declared but not defined (that is not pointed to any char variable). So, it's pointing to a garbage address and we are trying to write the value in an unallocated memory. It leads to wild pointer.

Ranjit said:   1 decade ago
It should be

char *ptr = (char *)malloc(30);

or

char *ptr;
ptr = (char*)malloc(30);


Then the output of the program will be "RAM".

Dolly said:   1 decade ago
Can't we say that malloc(30) wil return address of allocated memory (char)malloc(30) will convert it to char and then *ptr can hold it.

int example=1;
char *p=(char)example ; (is it equivalent to char *p="1"; )

I am confused. Please help ?

RAJU said:   1 decade ago
Address of allocated memory by using malloc should be stored in ptr i.e. pointer to an character. Then only it will work perfectly.

Hema said:   1 decade ago
It is not a character conversion it should be pointer to character when returned from malloc().
(1)

Post your comments here:

Your comments will be displayed after verification.