추가 된 각 요소 당 행 수가 증가하는 동적 unsigned char 배열을 만들려고합니다.
#include <stdio.h>
#include <stdlib.h>
#define BLOCKSIZE 1
int main()
{
unsigned char **p = NULL, rows = 0;
// initialize p pointer to as the size of one char
p = malloc ( BLOCKSIZE * sizeof ( unsigned char *) );
// add 10 "TEST" elements
for (;rows < 10; rows++ )
{
if (rows > BLOCKSIZE) {
// allocate memory for each row
p = realloc (p, rows * sizeof ( unsigned char *) );
}
// allocate memory for each column
p[rows] = malloc (rows * sizeof (unsigned char ));
// add element
p[rows] = "TEST";
}
for (int i=0; i < rows; i++)
printf("%s\n", p[i]);
return 0;
}
코드는 다음을 실행할 때이 오류를 출력합니다.
realloc(): invalid next size
Aborted (core dumped)
누군가 내가 뭘 잘못하고 있는지 설명해 주시겠습니까?
realloc
전화 :p = realloc (p, rows * sizeof ( unsigned char *) );
사이클의 첫 번째 반복에서 rows
0 바이트를 할당하면 첫 번째 행이 할당을 유지할 수 없으며 이후 재 할당에서는 할당하는 포인터 수에 충분한 공간이 없으며 항상 필요한 것보다 하나가 적습니다. , 이로 인해 할당되지 않은 메모리에 대한 잘못된 액세스가 발생합니다.
최소한 1의 크기로 재 할당해야하며 블록 크기에 unsigned char*
포인터 자체 ( sizeof *p
)를 사용할 수도 있습니다 .
p = realloc (p, (rows + BLOCKSIZE) * sizeof *p);
malloc
는 충분한 공간을 예약하지 않습니다. 최소한 할당 한 문자열 크기와 널 종료자를위한 공간을 더해 4 + 1이어야합니다.p[rows] = malloc (5 * sizeof **p);
rows
최소한 int
유형 이어야 하며 이상적으로 size_t
는 배열을 인덱싱하는 데 사용되며 그럴 이유가 없습니다 unsigned char
.
그대로 "TEST"를 할당하면 메모리 누수가 발생합니다 p[rows]
. 이전에 할당 된 메모리 블록이 아닌 문자열 리터럴 을 가리키고 있습니다. 다음을 사용해야합니다.
memcpy(p[rows], "TEST", 5);
또는 strcpy
서명 된 char
.
고정 코드 ( 온라인 ) :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BLOCKSIZE 1
int main()
{
unsigned char **p = NULL;
size_t rows = 0;
p = malloc ( BLOCKSIZE * sizeof *p);
if(p == NULL){ //always check for allocation failure
return EXIT_FAILURE;
}
for (;rows < 10; rows++ )
{
if (rows > BLOCKSIZE) {
p = realloc (p, (rows + BLOCKSIZE) * sizeof *p );
}
if(p == NULL){
return EXIT_FAILURE;
}
//in this case the row is always 4 + 1 chars, but you can have different number of chars per row
p[rows] = malloc (5 * sizeof **p);
if(p[rows] == NULL){
return EXIT_FAILURE;
}
memcpy(p[rows], "TEST", 5);
}
for (size_t i=0; i < rows; i++)
printf("%s\n", p[i]);
return EXIT_SUCCESS;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다