Why can I assign a longer string to a pointer in C? -
#include <stdio.h> #include <stdlib.h> int main() { char *ptr = malloc(sizeof(char) * 1); ptr = "hello world"; puts(ptr); getchar(); }
im not malloc() expert isn't code supposed give error since allocated 1 byte assigned value contains 11 bytes *ptr pointer ?
or h stored in place assigned , rest of string goes in places after ?
you reassigning pointer 'ptr' block of memory, won't see error. however, block of memory (size 1) allocated "lost" , leads memory leak.
Comments
Post a Comment