简体   繁体   中英

How to allocate memory using this malloc statement?

I have this method that reads a file. A matrix to be more specific where the first two numbers are the rows and the columns. However when i try to allocate the memory using malloc and using the rows and columns the application crash.

The code I'm using is this one:

#include stdio.h
#include stdlib.h
#include stdlib.h

float * readFile(char* nombre, int*renglones, int*columnas){
FILE *fp;
fp=fopen(nombre,"r");

fscanf(fp,"%d",&renglones);

printf("el numero de renglones es %d\n",renglones);

fscanf(fp,"%d",&columnas);

printf("number of rows %d\n",columnas);
float value;

fscanf(fp,"%f",&value);
printf("el numero de columnas es %f\n",value);
fscanf(fp,"%f",&value);
printf("el numero de columnas es %f\n",value);
printf("no llegue a malloc");
float * res = malloc(*renglones**columnas*sizeof(float)); //memory reservation and the line that breaks the program 
printf("after malloc");



fclose(fp);
return 0;

}

I know that the includes are between <>

The final code is this one with the includes: stdio.h and stdlib.h

  float * readFile(char* nombre, int*renglones, int*columnas){
FILE *fp;
fp=fopen(nombre,"r");
fscanf(fp,"%d",renglones);
printf("el numero de renglones es %d\n",renglones);
fscanf(fp,"%d",columnas);
printf("el numero de columnas es %d\n",columnas);
float value;
float * res = (float*)malloc(*renglones**columnas*sizeof(float)); //Reserva de memoria
printf("llegue a malloc\n");
int i;
for(i=0;i<*renglones**columnas;i++){
        fscanf(fp, "%f",&value);
        res[i]=value;
        printf("dato %f\n",value);
}
printf("%d",i);
fclose(fp);
return res;

}

Thanks!

Your problem is that you do:

...
fscanf(fp,"%d",&renglones);
...
fscanf(fp,"%d",&columnas);
...

As a result, those 2 numbers (that you read from file) become pointers to renglones and columnas which you further dereference to calculate the size for malloc . For instance, if you read numbers 16 and 32 , then renglones points to 0x00000010 and columnas points to 0x00000020 . However, these memory cells obviously contain random garbage (from the point of view of your task), ie they probably contain arbitrarily huge numbers which when multiplied together give even bigger number, and malloc simply cannot allocate that much amount of memory, which ultimately results in crash.

Instead it should be:

...
fscanf(fp,"%d",renglones);
...
fscanf(fp,"%d",columnas);
...

since both renglones and columnas are pointers already. This way you would really fill the two int variables to which renglones and columnas point to, and get the expected behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM