Re: malloc question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, Apr 26, 2011 at 1:33 PM, Randi Botse <nightdecoder@xxxxxxxxx> wrote:
> Hi All,
>
> I want to ask malloc() behaviour, consider these codes;
>
> ...
> char *ptr = malloc(1);
> strcpy(ptr, "what");
> puts(ptr);
> ....
>
> Confusingly, the strcpy() copied all bytes to ptr, but I just manage
> to allocate ptr only for 1 byte, I guess I will have segfault here,
> why this happen? why the string successfully copied into ptr? , is
> those code legal?

You didn't get segfault because you were lucky.

Memory is allocated in multiples of page size (usually 4K).
The memory after your allocated byte is valid in your case.

thanks,
Daniel.
--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html


[Index of Archives]     [Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [C Programming]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

  Powered by Linux