pointers - c sizeof() leads to overflow? -
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char *p ; char *q ; char *l = "aaaaaasdfsfdqwecvxcxfwdsagfd" ; p = (char*)malloc(sizeof(l)) ; q = (char*)malloc(strlen(l)) ; strcpy(p, l) ; strcpy(q, l) ; printf("%s\n",p) ; printf("%s\n",q) ; printf("%d\n",strlen(l)) ; return 0 ; }
please @ this, when input characters within 23 characters, it's ok, while inputting characters more 23, images shows that, result displays messy code, why happened ? enter image description here
when sizeof
on pointer, size of pointer , not memory points to. typically either 4 or 8 depending on if you're on 32 or 64 bit system.
then strlen
returns length of string without null terminator.
both of these sizes small hold full string terminator, leading undefined behavior when strcpy
calls go out of bounds.
Comments
Post a Comment