ubuntu - C malloc doesn't work the way I expected it to -


i have no idea wrong code.

char *names; int = 6; names = (char *) malloc((i+1)*sizeof(char));  printf("%d", strlen(names)); 

0 result instead of 7, why?

//i learnt using malloc this: tomb = (double*) malloc(n*sizeof(double));

line line...

int len1 = 0; int = 6; 

these should both size_t.

names = (char *) malloc((i+1)*sizeof(char)); 

you did not show variable declaration names. going assume char *, in future make sure show variable declarations all variables, or better, provide complete test program can compile , run ourselves if have to.

in c, not cast return value of malloc. in c-family languages, not write sizeof(char), 1 by definition.

you need check whether malloc failed (returned null).

while (names[len1] != '\0') 

undefined behavior on line, because memory returned malloc uninitialized. loop may iterate any number of times, including zero, seven, six, five, four, three, two, one, eight, nine, ten, 4096, , infinity. entitled crash program or make demons fly out of nose.

    len1++; 

also, have reinvented strlen.

printf("%d", len1); 

need \n after %d.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -