Wednesday 15 April 2015

C memory allocation affects char array length -



C memory allocation affects char array length -

#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { //step 1 char *key = malloc(10000); int *arr = malloc(sizeof(int)); free(arr); free(key); //step 2 char *msg = malloc(10000); printf("size: %zu \n", strlen(msg)); free(msg); homecoming 0; }

could explain this:

if execute both step 1 , 2, length of msg 6, 4 if exectue both step 1 , 2, without allocation , freeing of key, length 0 if execute step 2, length of msg 0

why allocation of int , key array impact length of char array? realize strlen requires '\0' char, why behave different?

char *msg = malloc(10000); printf("size: %zu \n", strlen(msg));

msg allocated, not initialized, undefined behavior phone call strlen(msg).

in cases, perhaps happens in uninitialized memory allocated malloc, first 0 appeared @ different places.

c arrays memory allocation

No comments:

Post a Comment