[英]Dynamic scan for a string : C
考慮下面我寫的代碼:
#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;
}
我正在嘗試實現字符數組的動態scannig。 工作正常。 我已經看到代碼運行到大型數組,例如說調整為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)
看來您應該更改此行:
*str=(char*) realloc(*str,j*sizeof(char));
對此:
*str=(char*) realloc(*str,j*10*sizeof(char));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.