Multi-level pointers in function parameters

Today, I was embarrassed by several segfaults, stack overflows, and free incorrect pointer errors.

I used to be a little confused about the use of multi-level pointers + function parameters, but today I really have a few troubles.

Here I want to extract several data with the same conditions from mysql, just fill it in line by line...
define a mysqlMsg*cur=NULL; and then use &cur to pass in the following function to dynamically allocate memory space for cur.

But I started using this piece of memory as a matter of course.

int mysqlGetMsgByUid(MYSQL mysql,int uid,mysqlMsg**mMsgList,int *mNum)
{
    
    
……
     *(mMsgList)=malloc(num_rows*sizeof(mysqlMsg));
     while(……){
    
    
          (mMsgList[i])->id=atoi(row[0]);
                (mMsgList[i])->type=atoi(row[1]);
                (mMsgList[i])->send_id=atoi(row[2]);
                strncpy((mMsgList[i])->message,row[3],MYSQL_MSG_SIZE);
                (mMsgList[i])->status=atoi(row[4]);
                (mMsgList[i])->flag=atoi(row[5]);
                (mMsgList[i])->recv_id=uid;
              i++;
              }  
……
}

In fact, mMsgList[i] is equivalent to *(mMsgList+i), that is, it crosses i×num_rows*sizeof(mysqlMsg)such a large interval, and when i>1, it exceeds the interval size we allocate.
So the following appeared

free(): invalid pointer
已放弃 (核心已转储)

What is the correct operation? ? ?
The double pointer is dereferenced first, and then offset by i sizeof(mysqlMsg) and then assigned.

     (*(mMsgList)+i)->id=atoi(row[0]);
                (*(mMsgList)+i)->type=atoi(row[1]);
                (*(mMsgList)+i)->send_id=atoi(row[2]);
                strncpy((*(mMsgList)+i)->message,row[3],MYSQL_MSG_SIZE);
                (*(mMsgList)+i)->status=atoi(row[4]);
                (*(mMsgList)+i)->flag=atoi(row[5]);
                (*(mMsgList)+i)->recv_id=uid;

Of course, this is because I *mMsgListallocated memory space instead of mMsgList, otherwise the previous writing is correct

And if it is stored in the stack area char arglist[10][20]as the function parameter, because this parameter is really an array pointer of char(*arglist)[20]. Then arglist[i] also represents an array, there is no problem filling this memory with data, it will not directly cross a double array.

Ah, a solid foundation is very important!

Guess you like

Origin blog.csdn.net/adlatereturn/article/details/106167280