arrays - Loop ending condition is not working - C -
i have homework regarding dynamic arrays, therefore trying understand how works simple programs.
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { int cnt,i=0; char temp[1001]; char *obj[5]; scanf("%d",cnt); while(i<cnt){ scanf("%s",temp); obj[i]=malloc(sizeof(char)*(strlen(temp)+1)); obj[i]=temp; printf("%s\n",obj[i]); printf("%d\n",i); i++; } return 0; }
when "cnt" equal 5, reading stdin, program running forever, though ending condition meets. when "cnt" equal 5, assigning it, @ beginning of program (not using scanf) program works fine. might reason this?
this:
scanf("%d",cnt);
should be:
/* check return value of scanf(), returns number of assignments made, ensure variables have been assigned value. */ if (scanf("%d",&cnt) == 1) { }
as scanf()
requires address of cnt
.
also:
- don't cast result of
malloc()
. sizeof(char)
guaranteed1
can omitted space calculation inmalloc()
.- check result of
malloc()
ensure memory allocated. free()
whatevermalloc()
d.- prevent buffer overrun
scanf("%s")
specifying maximum number of characters read, must 1 less target buffer allow space terminating null character. in casescanf("%1000s", temp)
. - there no protection out of bounds access on array
obj
.while
loop's terminating conditioni<cnt
ifcnt > 5
out of bounds access occur, causing undefined behaviour.
this assigns address of temp
obj[i]
:
obj[i]=temp;
it not copy (and causes memory leak). use strcpy()
instead:
obj[i] = malloc(strlen(temp) +1 ); if (obj[i]) { strcpy(obj[i], temp); }
Comments
Post a Comment