我正在使用为数组分配空间
int **pml=0;
int **tmp=(int **)realloc(pml, 100 * sizeof(*pml));
pml=tmp;
并尝试分配二维
for ( i = 0; i < 100;i++){
pml[i]=(int *)malloc(10 * sizeof ( int ));
pml[i][0]=2; // for storing index
pml[i][1]=10; // for realoc
}
我试图实现的是:用户输入2个数字,第一个是索引,第二个是值,所以如果我输入3和5,数组应该看起来像
array{{2,10},{2,10},{2,10},{2,10,5}}
我用这个伏特加X=第一个数字,例如索引Y=值;
if(pml[X][0]==pml[X][1]){
pml[X][1]+=10;
pml[X]=(int *)realloc(pml[X], pml[X][1] * sizeof ( int );}
pml[X][pml[X][0]=X;
pml[X][pml[0]]+=1;
}
但随着输入量的增加,抛出分段故障Valgrind抛出此消息
==4270== Invalid read of size 8
==4270== at 0x400873: main (in ../a.out)
==4270== Address 0x5445f40 is 0 bytes after a block of size 2,400,000 alloc'd
==4270== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4270== by 0x4C2CF1F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4270== by 0x400778: main (in /../a.out)
==4270==
==4270== Invalid read of size 4
==4270== at 0x400876: main (in /../a.out)
==4270== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==4270==
==4270==
==4270== Process terminating with default action of signal 11 (SIGSEGV)
==4270== Access not within mapped region at address 0x0
==4270== at 0x400876: main (in /h../a.out)
==4270== If you believe this happened as a result of a stack
==4270== overflow in your program's main thread (unlikely but
==4270== possible), you can try to increase the size of the
==4270== main thread stack using the --main-stacksize= flag.
==4270== The main thread stack size used in this run was 8388608.
==4270==
==4270== HEAP SUMMARY:
==4270== in use at exit: 14,400,000 bytes in 300,001 blocks
==4270== total heap usage: 300,001 allocs, 0 frees, 14,400,000 bytes allocated
==4270==
==4270== LEAK SUMMARY:
==4270== definitely lost: 0 bytes in 0 blocks
==4270== indirectly lost: 0 bytes in 0 blocks
==4270== possibly lost: 0 bytes in 0 blocks
==4270== still reachable: 14,400,000 bytes in 300,001 blocks
==4270== suppressed: 0 bytes in 0 blocks
==4270== Rerun with --leak-check=full to see details of leaked memory
==4270==
==4270== For counts of detected and suppressed errors, rerun with: -v
==4270== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
Segmentation fault
这意味着一些realloc出现了错误,但我没有看到任何错误——我在哪里错误地重新分配了字段?
看起来您正在尝试创建一个动态数组或堆栈。你可以通过使用一个结构来极大地简化事情:
struct Stack {
int capacity;
int index;
int *data;
};
然后,你想要100个(不确定为什么)。。。
struct Stack *pml = malloc(100 * sizeof(struct Stack));
然后初始化
for (int i = 0; i < 100; i++) {
pml[i].capacity = 10;
pml[i].index = 0;
pml[i].data = malloc(10 * sizeof(int));
}
然后您可以使用功能设置数据
void Push(struct Stack *stack, int value) {
// Check for reallocation
if (stack->index == stack->capacity) {
stack->capacity *= 2; //Assumes capacity >= 1
stack->data = realloc(stack->data, sizeof(int) * stack->capacity);
}
// Set the data
stack->data[stack->index++] = value;
}
并称之为
Push(&pml[n], 234); // Where n < 100, is the nth stack in the array
当然,你需要在某个时刻free()
所有的东西。
(注意,您应该添加错误检查。)