Pointer becomes nothing for no apparent reason - c

Greetings!
I have a simple program in qt on c.
There are two pointers to type short, used to read from file and store bits from values read.
sample code:
//(input is a FILE* which is opened and passed to the function)
//(output is also a FILE* which is also opened and passed to the function)
//1. Variables declaration
short* sample_buffer;
int buffer_size=1;
short samples_read;
unsigned long value_x=7;
short* nzb_buffer;
short buffer_position=-1;
int i;
//2.Memory allocation
sample_buffer= malloc(sizeof(short)*buffer_size);
nzb_buffer = malloc(sizeof(short)*value_x);
....
//3. Read from infile, one short at time, process and write it to outfile
do
{
//3.1. Read from input file
samples_read = fread(sample_buffer,sizeof(short),buffer_size, input);
//3.2. Switch position inside nzb_buffer one to the right,
// going back to zero if out of bounds
buffer_position=(buffer_position+1)%value_x;
....
//3.3. Put least significant bit of the just read short into nzb_buffer
nzb_buffer[buffer_position]=sample_buffer[0]%2;
....
//3.4. Write the short we just read from infile to the outfile
for (i=0;i<samples_read;i++)
{
fwrite(sample_buffer,sizeof(short),1, output);
}
} while(samples_read==buffer_size);
I've let unreliant pieces of code out. If you need to see something else please tell me.
Problem is, after like 10 or 15 operations of the loop, it crashes with "Segmentation fault" signal. It crashes on the fwrite() function.
I debugged and i use watch on sample_buffer. For some reason, on one exact step, the operation nzb_buffer[buffer_position]=sample_buffer[0]%2 makes sample_buffer become 0x0 (i belive, it becomes a null pointer).
This cannot be overflowing on nzb_buffer because buffer_position for that operation is 3 (out of 7 allocated for the particular array in malloc). And since each loop makes one write operation and shifts the carry, the operation of writing into nzb_buffer[3] has already happened before in the loop and did not nullify the pointer that time.
I am totally clueless what may be happening here.
Anybody has any ideas what is going on or how do i debug it?
Thanks in advance!
PS: Added comments "what the code does"

Your exit condition for the loop seems to be misplaced. I would do:
samples_read = fread(sample_buffer,sizeof(short),buffer_size, input);
while(samples_read==buffer_size){
[...]
samples_read = fread(sample_buffer,sizeof(short),buffer_size, input);
}

Related

segmentation fault in C memcpy

I have a basic problem using memcpy and don't understand where the problem is. I show below the relevant parts of the code. The code seg. faults in the last right iteration of the loop. Why can't I index in to an memory area that is reserved?
Thank you in advance.
mystr->data = malloc(2048);
unsigned char buf[8500];
for (i=0;i<32;i++){
offset = i*256;
memcpy(&mystr->data[64*i],&buf[8+offset],64);
}
From the comments it'cs clear that my suspicion was right:
if sizeof( *mystr->data ) > 1 (because e.g. it's unsigned long long *data;) then you run beyond the end of the buffer because the offsets calculated by expressions like &mystr->data[64*i] are relative to the type, here it is mystr->data + 64*i*sizeof(*mystr->data) bytes which was up to 64*31*8 in your code.
You could either change the type, as you have done, or change the offsets (to &mystr->data[8*i] in your case) depending on what what seems 'right' semantically in your context

Why this is not working? Strings in C. If always true. WHY?

Please help me.
I don't know why this program is not working.
Sorry, but I needed to post whole code so it can be understanded clearly.
I tried to put str in txt file and then read it again and it is the same problem.
Also, I tried changing pointers with some other and then sompareing them and also the samo problem.
Arguments of program are:
1) txt file - with something like this - xyxxyyyxyxxyxyyxyxyxyyyyxxxx...
2) number - example - 2 - means that i need to group symbols in pairs
Output should be probaillity of any combination of x and y (xx,yy,xy,yx - for group of 2).
example:
p(xx)=0.4
p(yy)=0.1
p(yx)=0.5
p(xy)=0
BUT!
this is ALWAYS TRUE:
if (str==lista[i])
WHY?
I am struggling with it for hours. :(
I tried what others suggested:
Look at this:
http://i.imgur.com/SL1L8hc.jpg and
http://i.imgur.com/QwZGdgM.jpg
Weirdest one:
http://i.imgur.com/BIeLXOu.gif
WHOLE CODE:
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
typedef char * string;
int main(int argc, char *argv[]){
if (argc<3) {
return -1;
}
FILE *ul;
int mode,i,dane,j,razl;
char *str;
int brojac=0;
string lista[1000];
int pomlis[1000];
ul=fopen(argv[1],"r");
fseek(ul,0,SEEK_SET);
if (!ul){
return 1;
}
for (i=0;i<1000;i++){
lista[i]="nist";
pomlis[i]=0;
}
mode=atoi(argv[2]);
str=(char*)malloc(mode+1);
brojac=0;
razl=0;
while (fgets(str,sizeof(char)*mode+1,ul)!=NULL){
dane=0;
// printf("%s ",str); //da bi printao u konzolu
brojac++;
for (i=0;i<=razl;i++){
if (str==lista[i]){
pomlis[i]++;
dane=1;
}
}
if (dane==0){
if (lista[i]=="nist") i--;
lista[i+1]=str;
pomlis[i+1]=1;
razl++;
}
}
for (i=1;i<=razl;i++){
printf("p(%s)=%f\n",lista[i],pomlis[i]/((double)brojac));
}
fclose(ul);
return 0;
}
I tried all suggestions in the comments and nothing works. Does anyone knows the answer?
First of, sizeof(char) is 1 by definition. It doesn't make the code more readable.
The line
fgets(str,sizeof(char)*mode+1,ul);
reads into char *str which is allocated in
str=(char*)malloc(sizeof(char)*mode);
Which should omit the cast, and is too small to hold everything fgets() writes to it (by the +1 '\0').
In addition:
printf("p(%s)=%d\n",lista[i],pomlis[i]/brojac);
pomolis[i] and brojac are both integers, therefore the division will not return a fraction (float/double) but an integer again (most likely zero in your program).
Thank you all, edited, but, can I get answer? Why I am getting minuses on question if no one knows answer?
Well, try replacing the line
if (str==lista[i]){
with
if (!strncmp(str, &lista[i], mode){
and remove the line
fgets(str,sizeof(char)*mode+1,ul);
in the body of the while-loop (you are already calling fgets() in the while condition, don't call it twice)
Your code has many problems. I suggest reading about pointers, memory allocation and how strings work in c. Because of your typedef char * string i suppose you must be coming from a higher language then c. Forget that knowledge, you'll have big problems if you try to apply it here.
I've made it work, but I will not post the working code here, as I'm not interested in doing anyone's homework. I'll try to teach you what your problems are.
Your first problem is here:
for (i=0;i<1000;i++){
lista[i]="nist";
pomlis[i]=0;
}
Assigning "nist" to char * assigns the address of a constant string "nist" to the pointer. As the string is constant, if you later try to change something in it, you will fail.
You should use malloc, which allocates memory you can write to:
for (i=0;i<1000;i++){
lista[i]=(char*) malloc(5);
pomlis[i]=0;
}
Next, as others have explained, using == is quite different then using strncmp. You should use:
if (strcmp(str, lista[i])==0){
pomlis[i]++;
dane=1;
}
The next part makes absolutely no sense:
if (dane==0){
if (lista[i]=="nist") i--;
lista[i+1]=str;
pomlis[i+1]=1;
razl++;
}
First you're comparing to another pointer to constant string (note that "nist" you've initialized to doesn't have to be the same "nist" you have here). I really have no idea what you're trying to accomplish using i here.
I wrote it like this:
if (dane==0){
memcpy(lista[razl],str, sizeof(str));
pomlis[razl]=1;
razl++;
}
Try to understand this.
Finally, your for loops go to the limit i<=razl. As arrays are zero initialized, you should break before i hits razl.
if (str==lista[i])
Now, str and lista[i] are of type char*. That is they are pointers. In which case the == operator tests for equality of the pointer addresses. So, if this == operator evaluates true then the two pointers have the same address.
If you want to compare the value of the string then you must use strcmp().

Will this loop run infinitely?

I am sitting in a class and I am told by a very experienced teacher that the following code will terminate when the STACK memory gets completely filled by the program. Now I am not able to understand why? Below Is the source code :-
#include<stdio.h>
int main()
{
char i;
for (i = 120; i < 130; i++)
printf("\n%d", i);
return 0;
}
Now, the reason I feel that this loop will not terminate is because once the program runs, the variable is declared in one memory location which is not changing till the life of the program and we are only changing the value of the already declared variable. So, I wanted to ask the answer to this question. Also, if you think the teacher is right, please explain as well :)
Also, I tried running the program for a long time but the memory consumption did not increase by even a bit :|
The actions of the program depend on how your implementation defines char: it may be a signed or an unsigned type.
If it is unsigned, it outputs 10 numbers and terminates.
If it is signed, it will wrap at 127 and the next value is -128 - in most implementations. But according to the standard, it is undefined behaviour.
I don't see why it should eat up the complete stack - there is no recursion and no additional memory allocation, so that
told by a very experienced teacher that the following code will terminate when the STACK memory gets completely filled by the program
means "never" - because it just doesn't fill up the stack. It cannot have been such an experienced programmer/teacher – or the OP is not an experienced listener and has misunderstood something the teacher has told him.
the reason is simple as well as tricky :)
i is not an int, but a char.
This means that its range goes from -128 to +127.
While the loop increses the index, it will overflow at +128, so that the value in memory will be -127 again. This means that i is again smaller than 130! The loop continues on and on...
Now continue cheating :P
char is 1byte long -2^8 to 2^8-1 (-128 to 127) if you try to add 1 to 127 it will be -128 an overflow occurs.
printing the variable you will see the same .
change the declartion from
char i to int i
it never fills the stack as you are not declaring new variables or calling functions to fill the stack. so it's an infinite loop only
Yeah it will lead to infinite loop since i has been declared as char which ranges from -128 to +127 so it never reached 130
the time i reaches 127 it comes back to -128 and never reaches 130
http://ideone.com/iVLoHe

STM32 printf and RTC

* UPDATE *
Here is what I found. Whenever I had that function in there it wouldn't actually make the code lock up. It would actually make the read RTC I²C function very slow to execute, but the code would still run properly, but I had to wait a really long time to get past every time I read the RTC.
So there is an alarm interrupt for the RTC and this was triggering other I²C interactions inside the ISR, so it looks like it was trying to do two I²C communications at the same time, therefore slowing down the process. I removed the functions in the ISR and it's working now. I will keep investigating.
I am having this problem when programming an STM32F103 microcontroller using IAR 5.40. I have this function that if I try to printf a local variable it causes the code to freeze at another point way before it even gets to that function in question.
What could possibly be causing this?
This is the function:
u8 GSM_Telit_ReadSms(u8 bSmsIndex)
{
char bTmpSms[3] = {0};
itoa(bSmsIndex, bTmpSms, 10); // Converts the smsindex into a string
printf("index = %s\n", bTmpSms); // This printf caused the code to get stuck in the RTC // byte read function!
GSM_Telit_RequestModem("AT+CMGR=""1", 10, "CMGR", 5, 0);
return 1;
}
I tried this as well and this does not cause the lock I experienced:
u8 GSM_Telit_ReadSms(u8 bSmsIndex)
{
char bTmpSms[3] = {0};
itoa(bSmsIndex, bTmpSms, 10);
printf("index = 2\n");
GSM_Telit_RequestModem("AT+CMGR=""1", 10, "CMGR", 5, 0);
return 1;
}
There is no optimization enabled whatsoever and the code gets stuck when trying to read a byte out of my I²C RTC, but as soon as I remove this printf("index = %s\n", bTmpSms); or use this one instead printf("index = 2\n"); then everything is happy. Any ideas?
The bSmsIndex will never be more than 30 actually and even then the lock up happens wayyyy before this function gets called.
char bTmpSms[3] only has space for "99". If your bSmsIndex is 100 or greater, you will be trying to write to memory that doesn't belong to you.
Edit after the update
I don't have a reference to itoa on my local machine, but I found this one ( http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/ ). According to that reference, the destination array MUST BE LONG ENOUGH FOR ANY POSSIBLE VALUE. Check your documentation: your specific itoa might be different.
Or use sprintf, snprintf, or some function described by the Standard.
Some ideas:
If itoa() is not properly NUL-terminating the string, then the call to printf may result in the machine looking for the NUL forever.
pmg has a very good point.
Also, consider what type the first argument to itoa() is. If it's signed and you're passing in an unsigned integer, then you may be getting an unexpected minus sign in bTmpSms. Try using sprintf() instead.
The change in code is moving the rest of your code around in memory. My guess is that some other part of the code, not listed here, is bashing some random location; in the first case that location contains something critical, in the second case it does not.
These are the worst kinds of problems to track down*. Good luck.
*Maybe not the worst - it could be worse if it were a race condition between multiple threads that only manifested itself once a week. Still not my favorite kind of bug.
It seems that if I don't initialize the variable bTmpSms to something the problem occurs.
I also realized that it is not the printf that is the problem. It is the itoa function. It got me to check that even though I didn't think that was the problem, when I commented the itoa function then the whole code worked.
So I ended up doing this:
u8 GSM_Telit_ReadSms(u8 bSmsIndex)
{
char bTmpSms[4] = "aaa"; // I still need to find out why this is !!!
itoa(bSmsIndex, bTmpSms, 10); // Converts the smsindex into a string
printf("index = %s\n", bTmpSms); // This printf caused the code to get stuck in the RTC // byte read function!
GSM_Telit_RequestModem("AT+CMGR=""1", 10, "CMGR", 5, 0);
return 1;
}
This is the itoa function I got:
char itoa(int value, char* result, int base)
{
// Check that the base if valid
if (base < 2 || base > 36) {
*result = '\0';
return 0;
}
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do
{
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsr
qponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while (value);
// Apply negative sign
if (tmp_value < 0)
*ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr)
{
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return 1;
}
What's the value of bSmsIndex you're trying to print?
If it's greater than 99 then you're overrunning the bTmpSms array.
If that doesn't help, then use IAR's pretty good debugger - I'd drop into the assembly window at the point where printf() is being called and single step until things went into the weeds. That'll probably make clear what the problem is.
Or as a quick-n-dirty troubleshoot, try sizing the array to something large (maybe 8) and see what happens.
What's the value of bSmsIndex?
If more than 99 it will be three digits when converted to a string. When zero terminated, it will be four characters, but you've allocated only three to bTmpSms so the null may get overwritten and the printf will try to print whatever is after bTmpSms until the next null. That could access anything, really.
Try to disassemble this area with index = 2 vs. index = %s.

Stack Overflow Exploit in C

The question is actually about stack overflows in C.
I have an assigment that I can not get done for the life of me, I've looked at everything in the gdb and I just cant figure it.
The question is the following:
int i,n;
void confused()
{
printf("who called me");
exit(0);
}
void shell_call(char *c)
{
printf(" ***Now calling \"%s\" shell command *** \n",c);
system(c);
exit(0);
}
void victim_func()
{
int a[4];
printf("[8]:%x\n", &a[8]);
printf("Enter n: "); scanf("%d",&n);
printf("Enter %d HEX Values \n",n);
for(i=0;i<n;i++) scanf("%x",&a[i]);
printf("Done reading junk numbers\n");
}
int main()
{
printf("ls=736c --- ps = 7370 --- cal = 6c6163\n");
printf("location of confused %x \n", confused);
printf("location of shell_call %x \n", shell_call);
victim_func();
printf("Done, thank you\n");
}
Ok, so I managed to get the first question correctly, which is to arbitrarily call one of the two functions not explicitly called in the main path. By the way, this has to be done while running the program without any modifications.
I did this by running the program, setting N to 7, which gets me to the Function Pointer of the victim_func frame, I write a[7] with the memory address of confused or shell_call, and it works. (I have a 64 bit machine, thats why I have to get it to 7, since the EBI pointer is 2 ints wide, instead of 1)
My question is the following, how could I control which argument gets passed to the shell_code funcion? ie. how do I write a string to char* c.
The whole point is executing unix commands like ps etc, by running only the program.
I figured writing the EBI pointer with the hex representation of ps and setting the arg list of shell_call to that, but that didn't work. I also tried inputing argsv arguments and setting the arg list of shell_call to the arg_list of main, but didn't work either.
I think the second version should work, but I believe I'm not setting the arg list of the new stack frame correctly ( I did it by writing a[8] to 0, since its the first part of the function pointer, and writing a[9]=736c and a[10]=0000, but its probably not right since those are the parameters of victim_func. So how do I access the parameters of shell_call?
I probably shouldn't do your homework for you. But the basically:
You need to get a character buffer somewhere in memory to store the string you want to execute. Obviously, you can do this the same way you are getting the other functions called (i.e. you put the text on the stack as well). After you have that written, you need to write a pointer to it on to the stack in the location that the shell_code function expects to find its arguments.
The best way to figure this out without me doing all of the work for you is to write down your stack/memory contents on a piece of paper/whiteboard. Write down how it would look if you called shell_code normally from inside the program. Then write down what the stack looks like inside victum_func and figure out which things to change to get it to look like it would look "naturally" (of course keeping in mind some things are "don't cares" like the return address).
That's all the charity you're gonna get from me today! :-P
SoapBox already did a great job of leading you in the right direction.
For more information;
http://www.skullsecurity.org/wiki/index.php/Example_4
You need to manipulate the stack-frame of the caller (main()), and arrange it in such a way that returning to shell_call() from the epilog of the overflowed victim_func() the latter could find a settled stack as it was been called by the main.
In doing so you probably have to mangle the frame-pointer in the stackframe of the victim, that will be restored in %ebp by means of leave.

Resources