Home  >  Article  >  Backend Development  >  The problem that memset/sizeof function is invalid when PHP calls C++ extension

The problem that memset/sizeof function is invalid when PHP calls C++ extension

WBOY
WBOYOriginal
2016-08-08 09:21:012220browse

Question: In C++, I am accustomed to using the memset function to initialize the array, such as:

int sz = 100;
int *a = (int*)malloc(sizeof(int) * sz);
memset(a,0,sizeof(a));

The above code dynamically opens an int array a with a size of sz, and assigns the opened memory to ASCII code 0

When PHP called this C++ code (using url to call the PHP function), it was found that the memset function did not work. The memory of array a was not assigned, resulting in many errors in the subsequent program. The investigation revealed this problem

The reason: The fundamental reason is that when PHP calls C++, sizeof(a) does not return the size of the continuous memory space pointed by a, but only returns the size of the pointer itself, so memset does not play its due role.

Solution: In the third parameter of memeset, use sizeof(int) * sz instead of sizeof(a), and pass in the actual size of the array as a parameter, so that the memset function can work

PHP is calling the C++ extension Sometimes, many library functions involving pointers in C++ will have problems, and sometimes they have to be written by themselves. The reason may be the memory management mechanism problem when PHP calls the extension.

Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces the problem of invalid memset/sizeof function when PHP calls C++ extension, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn