int* InvBPSK(complex* Symbols, int ArraySize){
int *Bits = (int*)malloc(sizeof(int)*ArraySize);
if(!Bits){
printf("Failed to allocate memory");
}
else{
for(int i=0; i<= ArraySize - 1;i++){
if((double)creal(Symbols[i]) == -(1/sqrt(2)) && (double)cimag(Symbols[i]) == -(1/sqrt(2))){
Bits[i] = 1;
}
else{
Bits[i] = 0;
}
}
}
return Bits;}
I was trying to allocate memory in my c code using malloc but something was going wrong when trying to use the allocated memory. Changing the name of the pointer solved this issue.
Related
I have create my own malloc function and it works properly. but I want to create another malloc using only array without struct. Is that possible to create without struct? This is my code.
#include <stdio.h>
char memory[20000];
int freeMem=20000;
typedef struct{
int start;
int end;
}chunk;
void *MyMalloc(int size){
printf("\nMemory Size= %d ",size);
if(size==0){
printf("0 means no memory\n");
return 0;
}
int memsize=20000;
chunk *p=(chunk *)&memory[0];
if(freeMem >= size+sizeof(chunk)){
while(p<(chunk *)&memory[19999]){
if(p->start==0){
if(p->end !=0){
if(size+sizeof(chunk)< (p->end - (int)p)){
p->start=(int)p+8;
p->end=(int)p+8+size;
freeMem = freeMem-(size+8);
printf("free Mem : %d\n",freeMem);
return (int *)p->start;
}
else{
p=(chunk *)p->end;
continue;
}
}
else{
p->start=(int)p+8;
p->end=(int)p+8+size;
freeMem = freeMem-(size+8);
printf("free Mem : %d\n",freeMem);
return (int *)p->start;
}
}
p = (chunk *)p->end;
}
}
else{
printf("no space...!\n");
return 0;
}
}
void MyFree(void * p){
chunk *ptr = (chunk *)p;
ptr--;
freeMem=freeMem+(ptr->end - ptr->start)+sizeof(chunk);
if(ptr->start != 0){
printf("\nfreed Memory : %d\t",ptr->end - ptr->start);
ptr->start = 0;
}
else{
printf("\nno Such memory allocated!!!!!\n");
}
}
Roughly speaking, the basic mechanism to use would be the same. In MyMalloc, allocate 2*sizeof(int) space more, store the content of a chunk there and return the address behind the 2*sizeof(int). On deallocation, do the same process in reverse - subtract 2*sizeof(int) from the argument to access the content of which was stored in chunk before.
I am trying to allocate enough space for an array of pointers to structure(City) with
City **ptrArray = (City **)calloc(numberOfLines, sizeof(City*));
char tempArray[100];
char* temp = tempArray;
int slength;
for (int i = 0; i < numberOfLines; i++)
{ //Allocates enough memory for array of length of string
fscanf(fPtr, "%99[^:] %*c", tempArray);
slength = strlen(temp);
ptrArray[i] = (City*)malloc(sizeof(int)+(sizeof(char)*slength));
strcpy(ptrArray[i]->cityName, temp);
//fscanf(fPtr, "%d", ptrArray[i]->temperature);
}
This is where I read the data from a file into the array. The debugger(visual studio) only shows one cell in ptrArray and it seems that the data gets lost.
numberOfLines is an assigned int value.
tempArray is a temporary holding place for the strings read from the file.
temp is a pointer to tempArray.
Bonus issue: The commented out line at the bottom of the for loop breaks the code every time and I have no clue why.
edit: I added the code where I initialized temp and tempArray.
Also it is a weird call to malloc because the assignment specifies allocating exactly enough memory for the string and an int instead of having a maximum value for the string. And here is my struct
typedef struct{
int temperature;
char cityName[100];
}City;
Thank you very much for you help!
For dynamic allocation of cityName.
typedef struct{
int temperature;
char *cityName;// pointer to char
}City;
City **ptrArray = calloc(numberOfLines, sizeof(City*));
if ( ptrArray == NULL) {
printf ( "calloc failed\n");
exit(1);
}
char tempArray[100];
int slength;
for (int i = 0; i < numberOfLines; i++)
{
if ( ( fscanf(fPtr, "%99[^:] %*c", tempArray)) != 1) {
//handle problem - break or return or exit.
}
slength = strlen(tempArray);
ptrArray[i] = malloc( sizeof(City));// memory for structure
if ( ptrArray[i] == NULL) {
printf ( "malloc failed\n");
exit ( 1);
}
ptrArray[i]->cityName = malloc( 1 + slength));// memory for cityName + 1 for '\0'
if ( ptrArray[i]->cityName == NULL) {
printf ( "malloc failed\n");
exit (1);
}
strcpy(ptrArray[i]->cityName, tempArray);
if ( ( fscanf(fPtr, "%d", &ptrArray[i]->temperature)) != 1) {
//handle problem break or return or exit
}
}
Memory allocated should also be freed when it is no longer needed. numberOfLines and ptrArray may have different names outside this function and the corresponding names would be used instead.
for ( i = 0; i < numberOfLines; i++) {
free ( ptrArray[i]->cityName);
free ( ptrArray[i]);
}
free ( ptrArray);
I create a 2D array to simulator a cache. For each cache line, I use struct to define it. When i want initialize the cahce, something is wrong when using malloc. I have marked the wrong place in the code.
Thanks!
typedef struct {
int valid;
int tag;
int lruIndex;
} Line;
Line** initCache(int s, int E){
int i, j;
//int setSize = sizeof(Line *);
//int lineSize = sizeof(Line);
/* allocate memory to cache */
//printf("%d %d\n", setSize, lineSize );
Line** cache = NULL;
cache = (Line **)malloc((1 << s) * sizeof(Line *)); //set
//check for memory error
if (!cache)
{
printf("%s\n", "allocate memory failed 1111111");
exit(-1);
}
for (i = 0; i < (1 << s); i++){
cache[i] = (Line *)malloc(E * sizeof(Line)); <<<<<<< i think here something is wrong, cache[i] returns NULL and then print "allocate memory failed 22222222"
//check for memory error
if (cache[i])
{
printf("%s\n", "allocate memory failed 22222222");
exit(-1);
}
for(j = 0; j < E; j++){
cache[i][j].valid = 0; //initial value of valid
cache[i][j].lruIndex = j; //initial value of lruIndex 0 ~ E-1
}
}
return cache;
}
if (cache[i])
{
printf("%s\n", "allocate memory failed 22222222");
exit(-1);
}
exits when cache[i] is != NULL, what means you exit when memory is allocated.
To work correct way change condition to:
(cache[i]==NULL)
which will evaluate to TRUE, when malloc fails.
malloc((1 << s) * sizeof(Line *)
can be malloc (0 * 4) too !
also you can run out of memory.
The following code is not working correctly. I'm getting a segfault when I run the program. I ran my program through gdb and found out that the error is occuring in the fillArrays(int**,int) function.
GDB is displaying the following parameters for fillArrays(int**,int):
fillArrays (arrays=0x0,numArrays=3)
Here is the source code to my program
#include <stdlib.h> /* malloc and free */
#define MULTIPLIER 1
#define SMALL 10
#define BIG 20
void allocateSmallArrays(int **arrays,int numArrays) {
int index,freeIndex;
int outerIndex,innerIndex;
arrays = malloc(numArrays*sizeof(int*));
if(arrays == NULL) {
printf("out of memory\n");
exit(1);
}
for(index = 0;index < numArrays;index++) {
arrays[index] = malloc(SMALL*sizeof(int));
if(arrays[index] == NULL) {
printf("out of memory\n");
exit(1);
}
}
}
void fillArrays(int **arrays,int numArrays) {
int outerIndex,innerIndex;
for(outerIndex = 0;outerIndex < numArrays;outerIndex++) {
for(innerIndex = 0;innerIndex < SMALL;innerIndex++)
arrays[outerIndex][innerIndex] = 0;
}
}
void deallocateSmallArrays(int **arrays,int numArrays) {
int index;
for(index = 0;index < numArrays;index++)
free(arrays[index]);
free(arrays);
}
int main(void) {
int numArrays = (3 * MULTIPLIER);
int **arrays = 0;
allocateSmallArrays(arrays,numArrays);
fillArrays(arrays,numArrays);
deallocateSmallArrays(arrays,numArrays);
arrays = 0;
return 0;
}
I was under the assumption that since arrays was allocated in allocateSmallArrays, that passing it through fillArrays would 0 out the allocated arrays and then deallocate in the last function. How do I go about accomplishing this?
The problem is that allocateSmallArrays changes its own copy of the arrays pointer. So the result of the malloc is lost and after the function is done, in the caller arrays is still 0. You could:
Pass a triple pointer int ***arrays and do to *arrays everything you're doing to arrays
Return the pointer instead of void
A C FAQ deals with this very subject.
I am mallocing an array of c strings. After releasing it, I get the following error:
Assembler(87536) malloc: *** error for object 0x108500840: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Why is that? I am pretty sure I am doing the malloc correctly. I'm pretty experienced with memory management, but I am not sure why this is giving me an error. The array is should hold three strings, each of which is 2 characters long.
Here is how I am mallocing the array:
char **reg_store;
reg_store = malloc(3 * (sizeof(char*)));
if (reg_store == NULL) {
fprintf(Out, "Out of memory\n");
exit(1);
}
for (int i = 0; i < 3; i++) {
reg_store[i] = malloc(2 * sizeof(char));
if (reg_store[i] == NULL) {
fprintf(Out, "Out of memory\n");
exit(1);
}
}
Here is how I am freeing it:
for (int i = 0; i < 3; i++) {
free(reg_store[i]);
}
free(reg_store);
Here is what I have in between:
// Keeps a reference to which register has been parsed for storage
int count = 0;
char *reg = NULL;
char *inst_ptr // POINTS TO SOME STRING. EXAMPLE: $t2, $t1, $a0
while (1) {
// Parses the string in inst_ptr with dollar, comma and space as a delimiter.
reg = parse_token(inst_ptr, " $,\n", &inst_ptr, NULL);
if (reg == NULL || *reg == '#') {
break;
}
reg_store[count] = reg;
count++;
free(reg);
}
I am printing out reg after I call parse_token and it does print out correctly. I am also printing out reg_store[count] and it does also print out correctly.
Your problem is here:
reg_store[count] = reg;
free(reg);
and later
free(reg_store[i]);
reg is already freed and you free it another time (not talking about the problems with using it later). to fix this replace
reg_store[count] = reg;
with
strcpy(reg_store[count], reg);
or as suggested in the comments, since you know its two charaters, its better to memcpy it:
memcpy(reg_store[count], reg, 2);
I would suggest adding some printfs (or use the debugger) to see the values of all the malloced pointers just after they have been malloced. Then do the same just before they are freed, to make sure they are the same. Perhaps there is some other rogue code elsewhere in the program that is stomping over memory.
Your problem is in the "in between" code, in particular, right here:
reg_store[count] = reg;
count++;
free(reg);
You allocated reg_store[count] with malloc during your set up, then you overwrite the allocated value with reg and then free reg. The result is a memory leak from the original pointers that were in reg_store and a double-free on each element of reg_store when you try to clean everything up.
You need to copy reg into the memory already allocated in reg_store[count] (watching the size of course) or don't allocate any space for the elements of reg_store before the "in between" code at all.
The error was already pointed out so no need to write it again.
I can however point out that i don't like the way you are handling errors.
void freeRegStore(char** reg_store)
{
int i;
if (reg_store != NULL)
{
for (i = 0; i < 3; i++)
free(reg_store[i]);
free(reg_store);
}
}
char** allocRegStore()
{
int i;
char **reg_store;
reg_store = calloc(3 * (sizeof(char*)), 1);
if (reg_store != NULL)
{
for (i = 0; i < 3; i++)
{
reg_store[i] = malloc(2 * sizeof(char));
if (reg_store[i] == NULL)
{
freeRegStore(reg_store);
return NULL;
}
}
}
return reg_store;
}
In this method, the function allocRegStore will return NULL if there was not enough memory without leaving pieces around.
Then you can handle this case in main and not in the allocation function itself.
I disagree with the use of printf and exit inside functions.
int main()
{
char** reg_store = allocRegStore();
if (reg_store == NULL)
{
puts("Out of memory");
return 1;
}
... do your stuff
freeRegStore();
return 0;
}
I can also say that the memory used by this program will never go out of memory :) i would not worry about that.