[英]C: SEGFAULT with realloc on char **
Another one in my series of problems with this code. 我在这段代码中遇到的另一个问题。 I have below function which is comparing
arg
with every string in the array of strings reference
: 我具有低于该比较功能
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
is global char **
, but built up dynamically inside main as below: reference
是全局char **
,但是在main中动态构建如下:
reference = calloc(CHUNK, sizeof(char *));
Then some code, then: 然后是一些代码,然后:
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++;
}
The code running fine for test case where no need to realloc
arises, ie Number of input strings is less than CHUNK
. 对于不需要
realloc
测试用例运行的代码运行正常,即输入字符串数小于CHUNK
。 In case of realloc
, I'm getting SEGFAULT
from function. 在
realloc
情况下,我从函数中得到SEGFAULT
。 Below is for one of the run: 以下是其中一个运行:
Program terminated with signal 11, Segmentation fault.
#0 __strstr_sse42 (s1=0x3839393433333230 <Address 0x3839393433333230 out of bounds>, s2=0x6020c0 <cmp> "8956549122")
You need to put parenthesis for expression in realloc()
as 你需要在
realloc()
括号表达式
//---------------------------------v -------------------v
char *retalloc = realloc(reference,(current_size + CHUNK)*sizeof(char *));
Assume CHUNK=100
and current_size=200
, your code will allocate 200+100*8=1000 bytes
while you want (200+100)*8 = 2400 bytes
假设
CHUNK=100
且current_size=200
,您的代码将分配200+100*8=1000 bytes
而您想要(200+100)*8 = 2400 bytes
Also, make sure you assign retalloc
to reference
variable after reallocation. 此外,请确保在重新分配
retalloc
分配给reference
变量。
When realloc
actually reallocates the memory you pass to it, then that pointer you pass as an argument still points to the old memory area. 当
realloc
实际重新分配您传递给它的内存时,您作为参数传递的指针仍然指向旧的内存区域。 The realloc
function returns a pointer to the new memory, so you have to assign that to eg reference
. realloc
函数返回指向新内存的指针,因此您必须将其指定给例如reference
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.