Cant figure out why program is crashing in C - c

I have this code:
#include <stdio.h>
#include <math.h>
#define gridSize 400
void main() {
float grid[gridSize][gridSize];
short height[gridSize][gridSize];
short power[gridSize][gridSize];
}
I'm using visual studio 2010, the program seems to crash instantly when I run it. However this code:
#include <stdio.h>
#include <math.h>
#define gridSize 400
void main() {
float grid[gridSize][gridSize];
short height[gridSize][gridSize];
//short power[gridSize][gridSize];
}
Seems to work fine, and the program doesn't crash. What could be the problem?

Here grid height and power are auto variable and going to store in stack.
In any Os each process has some fixed default size stack.
Here you are allocating too much data on stack so process has no other memory left on stack for other operation. so it crash
you have two option
1> Increase stack size for this process
On Linux with gcc you can increase it by
–stack 16777216
adding this in gcc command
2> you can store this data on heap section by using malloc.

You're allocating too much stack. Move one or more into heap instead.

Just read the name of this website, stack overflow.
You can:
1, move those three arrays out of main function(maybe you will get a large .exe after compilation if you initialize those arrays).
or
2, use malloc().

Related

FILE opening code in C. I need an explanation why this code gives different outputs when run several times

#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *fp = fopen("temp.txt", "we");
printf("%p\n", fp);
return 0;
}
this code gives the following different outputs:
0x19ee260
0x1ef9260
0xbde8260
.
.
.
I need an explanation concerning the memory.
This is due to Address Space Layout Randomization. The FILE structure that fopen() returns a pointer to is in the process's heap memory, and ASLR means that the location of the heap will be different each time you run a program.

Why the address of the variables changes based on how I run the program?

I don't understand why the address of the variables changes based on how I run the program. I have this simple code in C:
#include <stdlib.h>
#include <stdio.h>
int main(){
char buffer[100];
gets(buffer);
printf("buf: %p\n", (void*)&buffer);
printf(buffer);
return 0;
}
before compiling I used this command to disable the randomization:
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
but this is what happens:
image
in the first execution the address of buffer is bffff084 in the second is bffff024
This happens because of Address Space Layout Randomization. Each time program starts, random number is added to stack address so it would be harder to predict absolute addresses of buffers and write injectable shell code.
Since your program is vulnerable to buffer overflow (due to usage of gets and statically allocated buffer), it does its work.

How do I properly allocate a memory buffer to apply double buffering in dosbox using turbo c?

Okay so I am trying to apply a double buffering technique in an emulated environment (DosBox) while using the IDE Turbo C++ 3.0 I am running windows 7 64bit(Not sure if that matters) and I have no clue how to properly execute the buffering routine in this environment.
The main problem I am having is that I can't seem to execute the following assignment statement:
double_buffer = (byte_t far*)farmalloc((unsigned long)320*200);
(Note that 320 and 200 are the screen sizes)...
I just get NULL for the assignment.
I tried changing the default RAM usage of the DosBox to 32 instead of 16, but that didn't do anything. I'm not sure if it's the emulator or there is something wrong with the code for Turbo C. (Note that it complies just fine).
Here is a sample program I found online:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <dos.h>
#include <string.h>
#include <alloc.h>
typedef unsigned char byte_t;
byte_t far* video_buffer = (byte_t far*)0xA0000000;
void vid_mode(byte_t mode){
union REGS regs;
regs.h.ah = 0;
regs.h.al = mode;
int86(0x10,&regs,&regs);
}
void blit(byte_t far* what){
_fmemcpy(video_buffer,what,320*200);
}
int main(){
int x,y;
byte_t far* double_buffer;
double_buffer = (byte_t far*)farmalloc((unsigned long)320*200);
if(double_buffer == NULL){
printf("sorry, not enough memory.\n");
return 1;
}
_fmemset(double_buffer,0,(unsigned long)320*200);
vid_mode(0x13);
while(!kbhit()){
x = rand()%320;
y = rand()%200;
double_buffer[y * 320 + x] = (byte_t)(rand()%256);
blit(double_buffer);
}
vid_mode(0x03);
farfree(double_buffer);
return 0;
}
Your problem is related to running your application within the Turbo-C IDE debugger. If you compile it and then exit the IDE and run it directly from the DosBox command line without the IDE it should work as expected.
When running via the IDE, the default debug option is to only allocate an additional 64KiB memory for your program's heap. This isn't enough to handle your request for the 64000 bytes (320*200). In the Turbo-C IDE pull down the options menu, click on debugger. You should get a screen that looks like this:
The default value for Program Heap Size is 64. Change it to the maximum 640 and then click Ok. Rerun your program and it should display randomly colored pixels on the display at random locations.

Different run time after Segfault in Infinite Recursive main()

Just as we know,
In Linux world, infinite recusive "main()" in userspace will receive "segmentation fault" messsage, which is actually caused by stack overflow. (just as the following code)
#include <stdio.h>
void main(void)
{
main ();
}
Experiment and Question:
Change code to:
#include <stdio.h>
int cnt = 0;
void main(void) {
printf("cnt %d\n", cnt++);
main();
}
Test environment:
x86-64 ubuntu,
gcc-4.6
I need your help and thanks in advance!
Why Segmentation fault happens in different "cnt" value:
cnt: 523614
cnt: 523602
cnt: 523712
cnt: 523671
This is probably due to Address space layout randomization. If you run the slightly modified example of your program:
#include <stdio.h>
int cnt = 0;
void main(void)
{
int a;
printf("cnt %d %p\n", cnt++, (void*)&a); fflush(stdout);
main();
}
you will see that the address of a is not consistent over various runs of the program. Probably the initial size of the stack is also slightly randomized resulting in a slightly different number of stack frames fitting in this space.
P.S: I've added a fflush so the output of the program can be safely piped through for example tail and grep, otherwise buffering may blur the actual last line of output.
P.S2: I had to change print into printf and add #include <stdio.h>.
P.S3: You should not use an optimization on your program, because otherwise a tail-call optimization will remove your recursion and your program will actually loop forever. My version of the program doesn't do that, because of the aliased a.

strndup call is currupting stack frames

I have seen a strange behavior with "strndup" call on AIX 5.3 and 6.1.
If I call strndup with size more than the size of actual source string length, then there is a stack corruption after that call.
Following is the sample code where this issue can come:
int main ()
{
char *dst_str = NULL;
char src_str[1023] = "sample string";
dst_str = strndup(src_str, sizeof(src_str));
free(dst_str);
return 0;
}
Does anybody have experienced this behavior?
If yes please let me know.
As per my observation, there must be a patch from OS where this issue got fixed. but i could not get that patch if at all there is any. Please throw some light.
Thanks & Regards,
Thumbeti
You are missing a #include <string.h> in your code. Please try that—I am fairly sure it will work. The reason is that without the #include <string.h>, there is no prototype for strndup() in scope, so the compiler assumes that strndup() returns an int, and takes an unspecified number of parameters. That is obviously wrong. (I am assuming you're compiling in POSIX compliant mode, so strndup() is available to you.)
For this reason, it is always useful to compile code with warnings enabled.
If your problem persists even after the change, there might be a bug.
Edit: Looks like there might be a problem with strndup() on AIX: the problem seems to be in a broken strnlen() function on AIX. If, even after #include <string.h> you see the problem, it is likely you're seeing the bug. A google search shows a long list of results about it.
Edit 2:
Can you please try the following program and post the results?
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *test1 = "abcdefghijabcdefghijabcdefghijk";
char *test2 = "012345678901234567890123456789";
char *control = "01234567890123456789012345678";
char *verify;
free(strndup(test1, 30));
verify = strndup(test2, 29); /* shorter then first strndup !!! */
fprintf(stderr,">%s<\n",verify);
if (strcmp(control, verify))
printf("strndup is broken\n");
}
(Taken from https://bugzilla.samba.org/show_bug.cgi?id=1097#c10.)
Edit 3: After seeing your output, which is >01234567890123456789012345678<, and with no strndup is broken, I don't think your version of AIX has the strndup bug.
Most likely you are corrupting memory somewhere (given the fact that the problem only appears in a large program, under certain conditions). Can you make a small, complete, compilable example that exhibits the stack corruption problem? Otherwise, you will have to debug your memory allocation/deallocation in your program. There are many programs to help you do that, such as valgrind, glibc mcheck, dmalloc, electricfence, etc.
Old topic, but I have experienced this issue as well. A simple test program on AIX 6.1, in conjunction with AIX's MALLOCDEBUG confirms the issue.
#include <string.h>
int main(void)
{
char test[32] = "1234";
char *newbuf = NULL;
newbuf = strndup(test, sizeof(test)-1);
}
Compile and run the program with buffer overflow detection:
~$ gcc -g test_strndup2.c
~$ MALLOCDEBUG=catch_overflow ./a.out
Segmentation fault (core dumped)
Now run dbx to analyze the core:
~$ dbx ./a.out /var/Corefiles/core.6225952.22190412
Type 'help' for help.
[using memory image in /var/Corefiles/core.6225952.22190412]
reading symbolic information ...
Segmentation fault in strncpy at 0xd0139efc
0xd0139efc (strncpy+0xdc) 9cc50001 stbu r6,0x1(r5)
(dbx) where
strncpy() at 0xd0139efc
strndup#AF5_3(??, ??) at 0xd03f3f34
main(), line 8 in "test_strndup2.c"
Tracing through the instructions in strndup, it appears that it mallocs a buffer that is just large enough to handle the string in s plus a NULL terminator. However, it will always copy n characters to the new buffer, padding with zeros if necessary, causing a buffer overflow if strlen(s) < n.
char* strndup(const char*s, size_t n)
{
char* newbuf = (char*)malloc(strnlen(s, n) + 1);
strncpy(newbuf, s, n-1);
return newbuf;
}
Alok is right. and with the gcc toolchain under glibc, you would need to define _GNU_SOURCE to get the decl of strndup, otherwise it's not decl'd, e.g.:
#include <string.h>
...
compilo:
gcc -D_GNU_SOURCE a.c
Thanks a lot for your prompt responses.
I have tried the given program.
following is the result:
bash-2.05b# ./mystrndup3
>01234567890123456789012345678<
In my program I have included , still problem is persistent.
Following is the strndup declaration in prepossessed code.
extern char * strndup(const char *, size_t);
I would like to clarify one thing, with small program I don't get effect of stack corruption. It is consistently appearing in my product which has huge amount of function calls.
Using strndup in the following way solved the problem:
dst_str = strndup(src_str, srtlen(src_str));
Please note: used strlen instead of sizeof as i need only the valid string.
I am trying to understand why it is happening.
Behavior i am seeing with my product when i use strndup with large size:
At the "exit" of main, execution is coring with "illegal instruction"
intermittently "Illegal Instruction" in the middle of execution (after strndup call).
Corrupt of some allocated memory, which is no where related to strndup.
All these issues are resolved by just modifying the usage of strndup with actual size of source string.
Thanks & Regards,
Thumbeti

Resources