[英]C: SEGFAULT with realloc on char **
我在這段代碼中遇到的另一個問題。 我具有低於該比較功能arg
用的字符串數組中的每個串reference
:
char compare(char *arg)
{
int iter=0;
char retchar='0';
while(iter < no_of_ref)
{
// printf("arg : %s , reference : %s \n",arg,reference[iter]);
if((strstr(reference[iter],arg) != NULL) || (strstr(arg,reference[iter]) != NULL))
{
retchar='1';
break;
}
iter++;
}
return retchar;
}
reference
是全局char **
,但是在main中動態構建如下:
reference = calloc(CHUNK, sizeof(char *));
然后是一些代碼,然后:
temp_in[pre_pip+1]='\0';
reference[no_of_ref]=malloc(strlen(temp_in) + 1);
strcpy(reference[no_of_ref++],temp_in);
memset(&temp_in,'\0',sizeof(temp_in));
pre_pip = -1;
printf("INDEX: %d, address : %p , val : %s\n",no_of_ref-1,reference[no_of_ref-1],reference[no_of_ref-1]); //DEBUG
}
/*If allocated buffer is at brim, extend it for CHUNK char * further*/
if(no_of_ref == (tr*CHUNK - 2))
{
current_size = tr*CHUNK*sizeof(char *);
char *retalloc = realloc(reference,current_size + CHUNK*sizeof(char *));
if(retalloc == NULL)
perror("ERROR on realloc");
else
{
printf("Realloced successfully: %p\n",retalloc);
tr++;
}
對於不需要realloc
測試用例運行的代碼運行正常,即輸入字符串數小於CHUNK
。 在realloc
情況下,我從函數中得到SEGFAULT
。 以下是其中一個運行:
Program terminated with signal 11, Segmentation fault.
#0 __strstr_sse42 (s1=0x3839393433333230 <Address 0x3839393433333230 out of bounds>, s2=0x6020c0 <cmp> "8956549122")
你需要在realloc()
括號表達式
//---------------------------------v -------------------v
char *retalloc = realloc(reference,(current_size + CHUNK)*sizeof(char *));
假設CHUNK=100
且current_size=200
,您的代碼將分配200+100*8=1000 bytes
而您想要(200+100)*8 = 2400 bytes
此外,請確保在重新分配retalloc
分配給reference
變量。
當realloc
實際重新分配您傳遞給它的內存時,您作為參數傳遞的指針仍然指向舊的內存區域。 realloc
函數返回指向新內存的指針,因此您必須將其指定給例如reference
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.