pointer being realloc'd was not allocated - c

Actually this is a pure C prog.when i compile with Xcode. error
message says "pointer being realloc'd was not allocated"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int LocateElem(int *p1,int e,int leng1);
void Display(int max, int array[]);
int GetElem(int * p, int pass);
int Union(int *p1,int *p2, int leng1, int leng2);
int ListInsert(int *p, int e, int lengA);
int* GetData(int* pArray, int Array_size);
void Show(int *p, int leng);
void InitList_Sq(int *L);
int *p_A,*p_B;
int m,n;
int main()
{
clock_t begin, end;
double cost;
begin = clock();
printf("How many elements of A u want:");
scanf("%d",&m);
if (m<0) {
printf("Error!");
return 0;
}
printf("How many elements of B u want:");
scanf("%d",&n);
if (n<0) {
printf("Error!");
return 0;
}
p_A=(int *)malloc(m*sizeof(int));
p_B=(int *)malloc(n*sizeof(int));
if (p_A==NULL) {
printf("Error allocating memory!\n"); //print an error message
return 0; //return with failure
}
if (p_B==NULL) {
printf("Error allocating memory!\n"); //print an error message
return 0; //return with failure
}
int *pLast_A, * pLast_B;
printf("Array A is :\n");
pLast_A=GetData(p_A, m);
printf("\nArray B is :\n");
pLast_B=GetData(p_B, n);
int newLeng;
newLeng=Union(p_A,p_B,m,n);
printf("\nThe Union set is :\n");
Show(p_A, newLeng);
free(p_A);
free(p_B);
end = clock();
cost = (double)(end - begin) / CLOCKS_PER_SEC;
printf("\n%lf seconds", cost);
return 1;
}
int* GetData(int* pArray, int Array_size){
int* pFill= pArray;
int count;
srand((unsigned) time(NULL));
for ( count=0; count< Array_size; count++) {
*(pFill+count)=rand()%1000;
printf("%d\t", * (pFill+count));
}
return pFill+count;
}
int Union(int *p1,int *p2, int leng1, int leng2){
for (int count=0; count<leng2; count++) {
int e=GetElem(p2, count);
while(LocateElem(p1, e, leng1)==0){
leng1=ListInsert(p1, e, leng1);
}
}
return leng1;
}
int GetElem(int *p, int pass){
return *(p+pass);
}
int LocateElem(int *p1,int e,int leng1){
for (int count=0; count<leng1; count++)
if (e==*(p1+count))
return 1;
else
return 0;
}
int ListInsert(int *p, int e, int lengA){
lengA+=1;
int* temp;
temp=(int*)realloc(p, lengA*sizeof(int));
if (temp==NULL) {
printf("Error allocating memory!\n"); //print an error message
free(temp);
return 0; //return with failure
}
else{
p=temp;
*(p+lengA-1)=e;
}
return lengA;
}
void Show(int *p, int leng){
for (int count=0; count<leng; count++) {
printf("%d\t", *(p+leng));
}
}
After compilation xcode gives the breakpoint at the line temp=(int*)realloc(p, lengA*sizeof(int)) with signal SIGABRT.

The problem is that here:
int ListInsert(int *p, int e, int lengA){
int* temp;
temp=(int*)realloc(p, lengA*sizeof(int));
...
else {
p=temp; // <<<<< THIS
the new value of p does not propagate back to the ListInsert's caller. This happens because p is passed by value.
You need to turn int *p into int **p.

Related

function for multiple occurrences in linear search using pointer

This is the code i wrote for multiple occurrences in linear search.Can you please help me point out the mistake ? I want the function to store multiple values in the pointer array and then later to print the array
#include <stdio.h>
void linearsearch(int n,int a[n],int x,int count,int *b[count])
{
count=0;
int i;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
count+=1;
}
}
int j=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
b[j]=i;
j++;
}
}
}
int main()
{
int n;
scanf("%d",&n);
int a[n];
int i;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int x;
scanf("%d",&x);
int count;
int *b[count];
linearsearch(n,a,x,count,b);
for(i=0;i<count;i++)
{
printf("%d",*b[i]);
}
return 0;
}
I think there are several errors.
count must be initialized, like int count = 0;
count variable is not changed after linearsearch function.
b array should allocated dynamically.
suggested patch is:
#include <stdio.h>
void linearsearch(int n,int a[n],int x,int *count,int **b)
{
count=0;
int i;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
count+=1;
}
}
int j=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
*b = realloc(*b, sizeof(int) * (j + 1));
(*b)[j]=i;
j++;
}
}
}
int main()
{
int n;
scanf("%d",&n);
int a[n];
int i;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int x;
scanf("%d",&x);
int count = 0;
int *b = NULL;
linearsearch(n,a,x,&count,&b);
for(i=0;i<count;i++)
{
printf("%d",b[i]);
}
return 0;
}
Well the ideal way would be to allocate the memory dynamically based of the number of x found. But well let's look at the errors first. Maybe after this discussion you can write the code.
b[j]=i;
In the called function let's dissect the type of this.
i is of type int. And b[j] is of type int*. Then you assigned them (type mismatched). Then %d expects an int but you passed something of type int*. This is undefined behavior.
Now there was another flaw you had - you passed count and somehow you expect the value you changed in search will be there in main(). C is pass by value and you changed to a local variable. That change is lost when the called function ends.
#include <stdio.h>
#include <stdlib.h>
int* linearsearch(int n,int* a,int x,int* count)
{
*count=0;
if( n <= 0){
fprintf(stderr, "%s\n","Error" );
exit(1);
}
int *t = malloc(sizeof(*t)*n);
if( t == NULL){
perror("Malloc failed");
exit(1);
}
for(int i = 0; i < n; i++)
if(a[i] == x)
t[(*count)++] = i;
int *temp = realloc(t,sizeof(*temp)* (*count));
if( temp == NULL){
perror("Realloc failed");
exit(1);
}
t = temp;
return t;
}
int main(void)
{
int n;
if( scanf("%d",&n)!= 1){
fprintf(stderr, "%s\n", "Error in input");
exit(1);
}
if( n <= 0 ){
fprintf(stderr, "%s\n", "Error in input : must be greater than 0");
exit(1);
}
int a[n];
for(int i=0; i < n; i++)
if(scanf("%d",&a[i])!=1){
fprintf(stderr, "%s\n","Error in input." );
exit(1);
}
int elmt_to_find;
if( scanf("%d",&elmt_to_find)!= 1){
fprintf(stderr, "%s\n", "Error in input : Element to find(must be integer)");
}
int count;
int *b = linearsearch(n,a,elmt_to_find,&count);
for(int i = 0; i < count; i++)
printf("%d ",b[i]);
printf("%s","\n");
free(b);
return 0;
}
If you want to stick with using VLA for b, you can alter your linearsearch to return count only if b is NULL. Then, you can create b as VLA, and pass it back to linearsearch again to be populated.
int count = linearsearch(n, a, x, 0, 0);
int b[count];
linearsearch(n, a, x, count, b);
Then, your function could look like:
int linearsearch(int n,int a[n],int x,int count,int *b[count])
{
int i;
if(count==0)
{
for(i=0;i<n;i++)
{
if(a[i]==x)
{
count+=1;
}
}
}
if (b==0)
{
return count;
}
int j=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
b[j]=i;
j++;
}
}
return count;
}

[C Programming]Vectors & Pointers

I don't have idea where is the problem but the latest pointer(vector) have some troubles.
First value it's ok (V[0]+T[0]) , S[1] it's always 0 and third value it's random.
#include <stdio.h>
#include <stdlib.h>
int citire_vector(int n, int *V);
void afisare_vector(int n, int *V);
int produs_scalar(int n, int *V, int *T);
int suma_vectori(int n, int *V, int *T);
int main(void)
{
int n, *X, *Y, ps, *S;
printf("n = ");
scanf("%d",&n);
X = (int*) malloc(n*sizeof(int));
Y = (int*) malloc(n*sizeof(int));
citire_vector(n,X);
citire_vector(n,Y);
afisare_vector(n,X);
afisare_vector(n,Y);
ps = produs_scalar(n,X,Y);
printf("Produsul scalar = %d\n",ps);
S = (int*) malloc(n*sizeof(int));
*S= suma_vectori(n,X,Y);
afisare_vector(n,S);
}
int citire_vector(int n, int *V)
{
int i;
for(i=0;i<n;i++)
scanf("%d",V+i);
return *V;
}
void afisare_vector(int n, int *V)
{
int i;
printf("Valorile vectorului sunt:\n");
for(i=0;i<n;i++)
printf("%d ",*(V+i));
printf("\n");
}
int produs_scalar(int n, int *V, int *T)
{
int i, ps = 0;
for(i = 0;i<n;i++)
ps += (*(V+i))*(*(T+i));
return ps;
}
int suma_vectori(int n, int *V, int *T)
{
int i, *U;
for(i=0;i<n;i++)
{
*(U+i )= *(V+i);
}
return *U;
}
Your suma_vectori and its usage are incorrect.
Pointer U inside suma_vectori is uninitialized, causing undefined behavior on assignment
Assignment *S= suma_vectori(n,X,Y) has no effect beyond the initial element of S
To fix this problem, change suma_vectori to return int*, move malloc of the result inside the function, remove malloc for S, and assign S the result of the suma_vectori call:
int *suma_vectori(int n, int *V, int *T); // forward declaration
int *suma_vectori(int n, int *V, int *T) { // Implementation
int *U = malloc(n*sizeof(int)); // do not cast malloc
for(int i=0;i<n;i++) {
U[i] = V[i] + T[i];
}
return U;
}
// call
S= suma_vectori(n,X,Y);
// Don't forget to free malloc-ed memory
free(X);
free(Y);
free(S);
You have to allocate memory to U in suma_vectori function
as it is picking garbage value

Using pthreads and the code doesn't even get to main method

I am doing an assignment for school and I am supposed to make the following code (which generates pgm image with a Buddhabrot fractal) parallel.
Thing is the compiler doesn't point any errors and still the code won't even get to main. I have already tried looking it up but didn't find a way to solve it.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#define NT 3
int nColumns, nLines, size, ite, proximo;
double dt, x, y;
float **mat;
pthread_mutex_t mutex;
pthread_cond_t condM;
pthread_cond_t condE;
typedef struct {
int x;
int y;
} int2;
typedef struct{
double x;
double y;
} double2;
int2 coordinatesConversion(double x,double y, int nColumns,int nLines){
int2 ret;
int2 retError;
retError.x=-1;
retError.y=-1;
ret.x=round(((2.0+x)/3.5) *((double)(nColumns-1)));
ret.y=round(((1.5+y)/3.5) *((double)(nLines-1)));
if(ret.x<0 || ret.x>=nColumns) return retError;
if(ret.y<0 || ret.y>=nLines) return retError;
return ret;
}
int printMatrixToFilePGM(float **mat,int tamx, int nLines, char *srcFile){
FILE *arq=fopen(srcFile,"w");
int cont, cont2;
float min,max;
min=mat[0][0];
max=mat[0][0];
for(cont=0;cont<nLines;cont++)
for(cont2=0;cont2<tamx;cont2++){
if(min>mat[cont][cont2]) min=mat[cont][cont2];
if(max<mat[cont][cont2]) max=mat[cont][cont2];
}
max=max*0.35;
float delta = max-min;
fprintf(arq,"P2 \n");
fprintf(arq,"%d\n%d \n",tamx,nLines);
fprintf(arq,"255\n");
for(cont=0;cont<nLines;cont++)
for(cont2=0;cont2<tamx;cont2++){
int valpixel=((mat[cont][cont2]-min)/delta)*255.0f;
if(valpixel>255) valpixel=255;
fprintf(arq,"%d \n", valpixel);
}
fclose(arq);
}
float** mallocFloatMatrix(int tamx, int nLines, float defaultValueOfTheElementsAtMatrix){
float **errorCodeReturn=0x0;
float **mat;
int i,j;
int condErrorMalloc=0;
mat=malloc(sizeof(float *)*nLines);
if(mat==0x0) return errorCodeReturn;
for(i=0;i<tamx;i++) mat[i]=malloc(sizeof(float )*tamx);
for(i=0;i<tamx;i++)
if(mat[i]==0x0){
condErrorMalloc=1;
break;
}
if(condErrorMalloc==0) return mat;
for(i=0;i<nLines;i++) for(j=0;j<tamx;j++) mat[i][j]=defaultValueOfTheElementsAtMatrix;
for(i=0;i<tamx;i++) if(mat[i]!=0x0) free(mat[i]);
free(mat);
return errorCodeReturn;
}
void freeFloatMatrix(float **mat,int tamx, int nLines){
int i;
for(i=0;i<nLines;i++) if(mat[i]!=0x0) free(mat[i]);
free(mat);
}
int iteration(double x,double y, int nColumns,int nLines, int ite,int2 *iterationPath){
int cont;
int condInvalidPointer=1;
double2 z;
z.x=0.0;
z.y=0.0;
double2 c;
c.x=x;
c.y=y;
double2 zt;
for(cont=0;cont<ite;cont++){
zt.x=((z.x*z.x)-(z.y*z.y))+c.x;
zt.y=(2.0*(z.x*z.y))+c.y;
z=zt;
if(((z.x*z.x)+(z.y*z.y))>4.0){
if(cont>100) condInvalidPointer=0;
break;
}
iterationPath[cont]=coordinatesConversion(z.x,z.y,nColumns,nLines);
}
if(condInvalidPointer) return 0;
return cont;
}
void *mestre(void *param) {
int i;
for(i=0;i<size;i++){
x = -2.0+((double)i*dt);
for(y=-2.0;y<2.0;y=y+dt){
pthread_mutex_lock(&mutex);
proximo++;
pthread_cond_signal(&condE);
pthread_cond_wait(&condM, &mutex);
pthread_mutex_unlock(&mutex);
}
}
}
void *escravo(void *param) {
pthread_mutex_lock(&mutex);
if(proximo==0) pthread_cond_wait(&condE, &mutex);
double xe = x;
double ye = y;
proximo--;
pthread_cond_signal(&condM);
pthread_mutex_unlock(&mutex);
int k;
int2* iterationPath = (int2 *)malloc(sizeof(int2)*ite);
if(iterationPath==0x0) return 0x0;
int completedIterations = iteration(xe, ye, nColumns, nLines, ite, iterationPath);
for(k=0;k<completedIterations;k++){
if(iterationPath[k].x!=-1 && iterationPath[k].y!=-1)
mat[iterationPath[k].x][iterationPath[k].y]=mat[iterationPath[k].x][iterationPath[k].y]+1.0f;
}
free(iterationPath);
}
int main(void){
printf("Main method has started.");
pthread_mutex_init(&(mutex), NULL);
pthread_cond_init(&(condM), NULL);
pthread_cond_init(&(condE), NULL);
nColumns=2048;
nLines=2048;
dt=0.001;
size=round(4.0/dt);
ite=600;
proximo = 0;
mat=mallocFloatMatrix(nColumns,nLines,0.0f);
if(mat==0x0) return 0;
pthread_t m;
pthread_t escravos[NT-1];
pthread_create(&m, NULL, mestre, (void*)0);
int i;
for(i=0; i<NT-1; i++) pthread_create(&escravos[i], NULL, escravo, (void*)0);
pthread_exit(NULL);
printMatrixToFilePGM(mat,nColumns,nLines,"saida5.pgm");
freeFloatMatrix(mat,nColumns,nLines);
return 0;
}

Return an array in c with pointers

I am trying to make a program that makes simple things. Actually, I know how to do it but in an easier way without pointers and stuff. However, I wondered how I could do it differently (like I did below). Obviously, there is something I miss about pointers, I did the math, but still I cannot get its philosophy.
Thank you!
long *read_array(int n1, int n2)
{
int i, j;
long a[n1][n2];
for(i=0;i<n1;i++)
for(j=0;j<n2;j++)
printf("Fill the table");
a[i][j]=GetLong();
return a;
}
long *Min_of_Rows(int m, int n, long *a)
{
long B[];
int i, j;
for(i=0;i<m;i++)
B[i]=a[i][0];
for(j=0;j<n;j++)
if (a[i][j]<B[i])
B[i]=a[i][j];
return B;
}
void *Print_B_array (int M, long *b)
{
int i;
for(i=0; i<M; i++)
printf("%ld\n",b[i]);
}
main()
{
long *a, *b;
int n1, n2;
printf("give rows");
n1=GetInteger();
printf("give columns");
n2=GetInteger();
a=read_array(n1, n2);
b=Min_of_rows(n1, n2, a);
Print_B_Array(n1, b);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long *read_array(int n1, int n2){
int i, j;
long a[n1][n2];
printf("Fill the table\n");
for(i=0;i<n1;i++){
for(j=0;j<n2;j++){
a[i][j]=GetLong();
}
}
long *ret = malloc(sizeof(a));
memcpy(ret, a, sizeof(a));
return ret;
}
long *Min_of_Rows(int m, int n, long *a){
long *B = malloc(m*sizeof(*B));
int i, j;
long (*A)[n] = (void*)a;
for(i=0;i<m;i++){
B[i]=A[i][0];
for(j=0;j<n;j++){
if(A[i][j]<B[i])
B[i]=A[i][j];
}
}
return B;
}
void *Print_B_Array (int M, long *b){
int i;
for(i=0; i<M; i++)
printf("%ld\n", b[i]);
}
int main(void){
long *a, *b;
int n1, n2;
printf("give rows:");
n1=GetInteger();
printf("give columns:");
n2=GetInteger();
a=read_array(n1, n2);
b=Min_of_Rows(n1, n2, a);
printf("min of rows\n");
Print_B_Array(n1, b);
free(a);
free(b);
return 0;
}

glibc detected - double free or corruption message occur when free (int ** type) in C Program

int main (void)
{
int i,j;
int n;
int **P;
int *d;
scanf("%d",&n);
d=(int*)malloc(sizeof(int)*(n+1));
P=(int**)malloc(sizeof(int*)*(n+1));
for(i=0;i<=n+1;i++)
P[i]=(int*)malloc(sizeof(int)*(n+1));
for(i=0;i<n+1;i++)
scanf("%d",&d[i]);
minimult(n,d,P);
order(1,n,P);
free(d);
for(i=0;i<n+1;i++)
free(P[i]);
free(P); //<----------------when execute here!!!!
return 0;
}
int minimum (int **M,int *d,int i, int j)
{
int count;
int temp,temp2;
for(count=i;count<=j-1;count++)
{
temp=M[i][count]+M[count+1][j]+d[i-1]*d[count]*d[j];
if(M[i][j]>temp||count==i)
{
M[i][j]=temp;
temp2=count;
}
}
return temp2;
}
int minimult(int n, int * d, int **P)
{
int i,j,k,diagonal;
int **M=(int**)malloc(sizeof(int*)*(n+1));
int result;
for(i=0;i<n+1;i++)
M[i]=(int*)malloc(sizeof(int)*(n+1));
for(i=1;i<=n;i++)
M[i][i]=0;
for(diagonal=1;diagonal<=n-1;diagonal++)
for(i=1;i<=n-diagonal;i++)
{
j=i+diagonal;
P[i][j]=minimum(M,d,i,j);
}
result=M[1][n];
for(i=0;i<n+1;i++)
free(M[i]);
free(M);
return result;
}
This algorithm is solving optimized matrix multiplication order.
Input was 4 2 3 4 5.
When I delete that line, it operates successfully.
What's the problem?
In your allocation loop for P[i], you loop one to many time and overwrite past the end of the allocated memory for P. Change the looping condition to i < n + 1 (or i <= n).

Resources