• C

Stuck when try to free pointer.


I´m  new to C, and i´m stuck with this error.
When i try to free te pointer a heap error ocurred. I try to figured out, with no sucess.
Every thing is working fine if i don´t try to free the pointer at the end of the program, but i want to free the pointer.
Can someone help me  understand what i´m doing wrong.

In attachement goes my code

Thank you all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#define MAX 100

float uniforme()//funçao que que gera valores entre 0 e 1
	float d;
	d = rand()%10000+1;
	d = d / 10000;
	return d;
char* memTamanho(char * buf, size_t NovoTam, size_t TamAntigo)
	void *newInput ; 
    newInput = realloc(buf, NovoTam);
	if (newInput == NULL)
		printf("Erro a realocar a memoria.\n");
		return NULL ; 
    return (char*)newInput;

/*Função que calcula os tempos de volta de cada Piloto*/
float tempos_volta(float *v_medios,int i)
	int n=0,k;
	float erros=0, prob_erro=0.5, val_aleatorio, tempo_volta=5.00, soma=0.0, aux=0.0, Mtempo[3]={'\0'};

			for(k=0; k<24;k++)
					/*chama a função que vai gerar o valor entre 0 e 1*/
			/*Condição que incrementa o numero de erros por volta*/
	/*Condição que analisa o melhor tempo das 3 voltas*/
	while (n<2)
	return aux;
/*Função que imprime a melhor volta das 3*/
void volta( float *v_medios, int i)
	float M_volta;
	int n=1;

			M_volta=tempos_volta (v_medios, i);
			printf("%d. Piloto (%.2f): %.2f\n",n, v_medios[i-1], M_volta);

/*Função que parte a string inserida, para dentro de um vector*/
void InsereVmedios(char *input_medios)
	float *v_medios;
	char *string;
	int i=0;

	v_medios=(float*) malloc(sizeof(float*)*i+1);
	string=(char*)strtok(input_medios," ");

			v_medios[i]=atof(string);//muda o valor de char para float
			string=(char*)strtok(NULL," ");

int main()
	char *input_medios, *buf, string;
	size_t tamMem = 1;
	size_t MemUsada = 0;

	buf= (char*)malloc((tamMem)*sizeof(char));
	if(buf == NULL)
			printf("Erro de memoria.\n");
			return -1;
	printf("Indique tempos medios dos pilotos, separados por espacos:\n");
	while ((string = fgetc(stdin))!= '\n')
			if (tamMem==MemUsada)
					MemUsada *= 2;
					buf= memTamanho(buf, tamMem, MemUsada);
					input_medios= buf + (MemUsada-1);
					if(buf== NULL)
						return -1;
	//free(buf); problem here
	return 0;

Open in new window

LVL 12
David Paris VicenteSystems and Comunications Administrator Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

In this line, you probably meant to double tamMem, instead of MemUsada :

>> 129:                               MemUsada *= 2;

And here :

>> 131:                               input_medios= buf + (MemUsada-1);

you probably need to add 1 more to input_medios, so it points to the next available position, and not to the last written character.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
David Paris VicenteSystems and Comunications  Administrator Author Commented:
Hi Infinity08

Thank you for your help.

I did like you said and work.

But i have another question if you don´t mind to explain.
As you can see in the function void InsereVmedios(char *input_medios)

 line 93: v_medios=(float*) malloc(sizeof(float*)*i+1);

I use again malloc to that pointer, so i have to free that pointer?(wright)
And i also have to free the input_medios variable?

I´m asking that because i try to free them but the some error appear.

But like i said maybe this are a newbie questions but i´m not confortable with C and less more with pointers and dynamic memory.

I´m very appreciated for your help.
Thanks again
>> I use again malloc to that pointer, so i have to free that pointer?(wright)


Basically, it comes down to this : for every allocation you do, you need a corresponding free. Since you call malloc inside the InsereVmedios function, you'll also need a corresponding free to de-allocate that memory again (otherwise you'd have a memory leak). You probably want to do that right before returning from the function.

>> And i also have to free the input_medios variable?

The input_medios function points to a block of memory that is already freed correctly by using free(buf) at the end of main. You should not de-allocate the same block of memory more than once - that's asking for trouble :)

>> But like i said maybe this are a newbie questions but i´m not confortable with C and less more with pointers and dynamic memory.

Practice makes perfect. By using dynamic memory allocation in your code, you'll get more and more comfortable with it. We've all had to learn how to use pointers and dynamically allocated memory correctly in C.
Get Certified for a Job in Cybersecurity

Want an exciting career in an emerging field? Earn your MS in Cybersecurity and get certified in ethical hacking or computer forensic investigation. WGU’s MSCSIA degree program was designed to meet the most recent U.S. Department of Homeland Security (DHS) and NSA guidelines.  

David Paris VicenteSystems and Comunications  Administrator Author Commented:
Thanks for the fast answer´s.

But i´m steel stuck again when try to free the v_medios.

Like you said i try to free the pointer v_medios at the end of the function, but no success. grrrrrr :(

Can you help me understand better how this works, or any good tutorial for me ( i have 6 years old, i´m kidding)

That's most likely because you don't allocate enough memory for v_medios :

>> 93:       v_medios=(float*) malloc(sizeof(float*)*i+1);

First of all, you need sizeof(float) instead of sizeof(float*), because you allocate memory for an array of float's, not pointers-to-float.
Next, you need ()'s around i+1. Otherwise, the +1 is performed after the multiplication.
Finally, you need to set i to a value that is big enough (instead of 0).
David Paris VicenteSystems and Comunications  Administrator Author Commented:
Thanks again.

What i do before you answer was, i pass the variable memUsada to the function where is the v_medios=(float*) malloc(sizeof(float*)*i+1);

And put like this v_medios=(float*) malloc(sizeof(float*)*memUsada); and did work. :)

But i don´t have the knowledge or skill yet to see if it´s well in programmatically way.

But the program run´s well now but if it is the wright way to do! hum i dont know.

Can you give your opinion as an expert?

Thanks a lot for your help and time.
Apart for the fact you still use sizeof(float*), your approach sounds reasonable - MemUsada is guaranteed to be big enough for the float array.
David Paris VicenteSystems and Comunications  Administrator Author Commented:
Thanks for your opinion.

I already change the sizeof(float*) to sizeof(float).

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.