Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need some explanation about malloc

Tags:

c

I don't understand it prints out OneExample when i allocated memory for 5. I know it is possible to do it using strncpy But is there a way to do it without using strncpy

It works with strncpy, but is there a way to do it without strncpy ?

void main()
{

    char *a;

    a=(char*)malloc(5);

    a="OneExample";
    printf("%s",a);

    free(a);

}

It prints out OneExample

Should not it print OneE ?? Can someone explain ?

void main()
{

    char *a;

    a=(char*)malloc(5);

    a="OneExample";
    printf("%s",a);

    free(a);

}
like image 202
Mondel Craguey Avatar asked Jan 27 '23 11:01

Mondel Craguey


1 Answers

You aren't using the memory you've allocated. After allocating the memory, you override the pointer a with a pointer to a string literal, causing a memory leak. The subsequent call to free may also crash your application since you're calling free on a pointer that was not allocated with malloc.

If you want to use the space you allocated, you could copy in to it (e..g, by using strncpy).

like image 134
Mureinik Avatar answered Feb 16 '23 02:02

Mureinik