-1

Consider below code I have written:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void dynamicScan(char** str)
{
 *str=(char*) malloc(10*sizeof(char));
 int i=0,j=1,k=0,c;
 do{
 c=getchar();
 *(*str+i)=c;
 i++;
 k++;
 if(k >=10)
 {
     j++;
     *str=(char*) realloc(*str,j*sizeof(char)); //Edited: Line 17 here
     assert(*str);
     printf("Resized to %d bytes\n",j*10);
     k=0;
 }
 }while(c != '\n');

 *(*str+i)='\0';
}


int main()
{

char* dynamicName,*dynAdd;

printf("-------------------------\n");
printf("Enter a Dynamic Name: ");
dynamicScan(&dynamicName);
printf("Dynamic Name: %s\n",dynamicName);
printf("Enter a Dynamic Address: ");
dynamicScan(&dynAdd);
printf("Dynamic Address: %s\n",dynAdd);


free(dynamicName);
free(dynAdd);


return 0;
}

I am trying to implement dynamic scannig of a character array. It works fine. I have seen the code running to large arrays .e.g say resized to 80 bytes. But many times code is crashing even for resizing to 20 bytes. Below is the dgb output. I am not able to figure out, what is going wrong, Can any help to debug?

(gdb) run
    The program being debugged has been started already.
    Start it from the beginning? (y or n) y
    Starting program: /cygdrive/d/cPractice/getS.exe
    [New Thread 8820.0x102c]
    [New Thread 8820.0x3d0]
    -------------------------
    Enter a Dynamic Name: Andrew Thomas from UK
    Resized to 20 bytes
    Resized to 30 bytes
    Dynamic Name: Andrew Thomas from UK

    Enter a Dynamic Address: I was living in scotland; now in united kingdom
    Resized to 20 bytes
    Resized to 30 bytes

    Program received signal SIGABRT, Aborted.
    0x00401206 in dynamicScan (str=0xd0) at getS.c:17
    17               *str=(char*) realloc(*str,j*sizeof(char));
    (gdb)
Gaurav K
  • 2,864
  • 9
  • 39
  • 68
  • 2
    Ugh, you should really indent your code before posting, and also remove commented out sections, and also indicate which like that line 17 is. – hyde Jun 04 '14 at 18:37
  • @hyde edited.. anyways got it.. wat was missing as pointed by jwodder in answer. – Gaurav K Jun 04 '14 at 18:39

1 Answers1

2

It appears that you should change this line:

*str=(char*) realloc(*str,j*sizeof(char));

to this:

*str=(char*) realloc(*str,j*10*sizeof(char));
jwodder
  • 54,758
  • 12
  • 108
  • 124
  • 1
    Please read: [Don't cast the result of malloc (and friends)](http://stackoverflow.com/questions/605845). Also, `sizeof(char)` is per definitionem 1. – Deduplicator Jun 04 '14 at 18:40