-
April 12th, 2004, 04:08 AM
#1
malloc issues
I have read and read, but I cant seem to find the answer...
I have written a program that calls this function:
Code:
char *ConvertToBinaryString(Ciphertext *cipher)
{
int i;
char *output;
output = (char *)malloc(sizeof(char));
strcpy(output, "");
for(i=0; i<64; i++)
{
if(cipher->cipher[i].bit == 1)
strcat(output, "1");
else
strcat(output, "0");
}
return output;
}//End of ConvertToBinaryString
In my main I call the function that calls the above function twice, sequentially. The first time, the function that calls the above function executes, everthing is fine and I get the desired output. The second time I call the function that calls this function, the malloc statement at the start of this function returns a NULL. I have tried time and time again to get around this. Does anyone have any ideas?
I have tried using preset array size (the output will always be a 64 byte string), but to no avail. This function comes at the end of the function that calls it, and I have stepped through it a thousand times. Malloc always returns NULL the second time I call the function. Thanks in advance.
-
April 12th, 2004, 04:11 AM
#2
additional info...
Not sure if it makes a difference, but the structure I send the function has 64 individual bits and the purpose of the function itself is to look at the bits and create a character string of 1's and 0's.
-
April 12th, 2004, 04:35 AM
#3
output = (char *)malloc(sizeof(char));
you have allocated a memory for a single char!
you cant use strcat on that pointer unless you allocate
enough memory to occupy that strcat.
according to your loop, it should be:
output = (char *)malloc(65*sizeof(char));
where 65 = (64 characters + 1 character for null terminator)
**** **** **** **** **/**
-
April 12th, 2004, 04:47 AM
#4
Hi,
***************************************************
output = (char *)malloc(sizeof(char));
...
strcat(output, "1");
***************************************************
How u can concat to a memory which is only one byte, u have to allocate some more memory. Looking at ur code (loop), it should be atleast 65 bytes.
ashish
-
April 12th, 2004, 02:38 PM
#5
I agree with the previous 2 posts, but it works once without initially allocating 65 bytes. I will try it though... thanks.
-
April 12th, 2004, 03:11 PM
#6
actually it didn't work, you just had luck (or unluck)
it didn't crashed before. you had accessed a memory
that is not belongs to you therefore one of the next scenarios
could happen:
1. your valus will be overriden
2. you override data that is in used not by you
each of these cannot be concidered as "worked"...
**** **** **** **** **/**
-
April 12th, 2004, 08:44 PM
#7
I got it working! Thanks for everyone's input.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|