动态扫描字符串:C

时间:2014-06-04 18:31:38

标签: c dynamic-memory-allocation

请考虑我写的代码:

#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;
}

我正在尝试实现字符数组的动态扫描。它工作正常。 我已经看到代码运行到大型数组。例如,调整大小为80 bytes。 但很多时候,即使调整大小到20 bytes,代码也会崩溃。 以下是dgb输出。我无法弄清楚,出了什么问题,可以帮助调试吗?

(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)

1 个答案:

答案 0 :(得分:2)

您似乎应该更改此行:

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

到此:

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