[英]Dynamic Memory Allocation in C ( return value 3221225477 & Segmentation fault: 11 )
Can anyone explain what is the wrong of the code below?谁能解释下面的代码有什么问题? İf I give the "line" variable as 1,2,3 or 4, it runs correctly.如果我将“line”变量指定为 1、2、3 或 4,它会正确运行。 But after 4 it just shows a count of row correctly, the count of columns is not correct.但是在 4 之后它只是正确显示了行数,列数不正确。
output of dev-c/c++ on windows >> "return value 3221225477" windows 上 dev-c/c++ 的 output >> “返回值 3221225477”
output of gcc on mac >> "Segmentation fault: 11" Mac上gcc的output >>“分段错误:11”
#include<stdio.h>
#include<stdlib.h>
int main(){
int **matris;
int size;
int i, j;
printf( "Size >> " );
scanf( "%d", &size );
matris = (int **)malloc( size * sizeof(int) );
if( matris == NULL )
printf( "It's required more memory'!" );
for( i = 0; i < size; i++ ) {
matris[i] = malloc( size * sizeof(int) );
if( matris[i] == NULL )
printf( "It's required more memory'!!" );
}
for( i = 0; i < size; i++ ) {
for( j = 0; j < size; j++ ){
matris[i][j]=i+1;
printf( "%d ", matris[i][j] );
}
printf( "\n" );
}
for( i = 0; i < size; i++ ) {
free( matris[i] );
}
free( matris );
return 0;
}
matris = (int **)malloc( size * sizeof(int) );
with especially ( size * sizeof(int) )
is wrong.特别是( size * sizeof(int) )
是错误的。 You need to allocate memory for objects of type int*
(pointer to int
), not int
.您需要为int*
(指向int
的指针)类型的对象分配 memory ,而不是int
。
This is a problem if sizeof(int) < sizeof(int*)
on your implementation -> Translated: The size of an object of type pointer to int
is bigger than the size of an object of type int
, which is quite common.如果您的实现中的sizeof(int) < sizeof(int*)
-> 已翻译:指向int
的类型指针的 object 的大小大于int
类型的 object 的大小,这很常见。
Then you get a segmentation fault, because you access memory beyond the bounds of the pointer array matris
in the following code.然后您会遇到分段错误,因为您在以下代码中访问了超出指针数组矩阵边界的matris
。
Use:利用:
matris = malloc ( sizeof(int*) * size );
or even better甚至更好
matris = malloc ( sizeof(*matris) * size );
Side Notes:旁注:
You don't need to cast the return of malloc()
.您不需要强制返回malloc()
。 The returned pointer is automatically aligned.返回的指针会自动对齐。 Do I cast the result of malloc? 我要转换 malloc 的结果吗?
sizeof(*matris)
requires less maintenance and is more safe if the type of matris
and the pointed objects changes. sizeof(*matris)
需要较少的维护,如果matris
类型和指向对象发生变化,则更安全。
Set the sizeof
operation first to ensure size_t
arithmetic, since size
is of type int
.首先设置sizeof
操作以确保size_t
算术,因为size
是int
类型。
The line matris = (int **)malloc( size * sizeof(int) );
行matris = (int **)malloc( size * sizeof(int) );
is incorrect as you want to create an array of int pointers and not of int.不正确,因为您要创建一个 int 指针数组而不是 int。 Changing the int
to int*
works.将int
更改为int*
有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.