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) guaranteed 1 can omitted space calculation in malloc().
  • check result of malloc() ensure memory allocated.
  • free() whatever malloc()d.
  • prevent buffer overrun scanf("%s") specifying maximum number of characters read, must 1 less target buffer allow space terminating null character. in case scanf("%1000s", temp).
  • there no protection out of bounds access on array obj. while loop's terminating condition i<cnt if cnt > 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

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -