V
Vishal Grover
Hello Everyone,
I am seeing a certain behaviour which I find strange, and am curious to get an
explanation to it. I have the following program.
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char ** argv) {
if(argc<2) {
return -1;
}
int value = atoi(argv[1]);
char * arr = new char[value];
// No segmentation fault unless next is an array.
char * next = new char[value];
int i = 0;
for(i=0; i<value; i++) {
arr = 'a';
next = 'a';
}
// NOTE: I am adding a char beyond the array boundary
arr='\0';
next='\0';
// This causes a segmentation fault
delete [] arr;
}
I compiled this with 3.2.2 on Red Hat Linux 9 on an Intel i686. When I run the
program, it gives me a Segmentation fault only when the array size is an odd
multiple of 4. My guess is it has something to do with word alignment. But, what
exactly is happening here?
Thanks for your help,
Vishal Grover
Developer
Trilogy Software Inc.
I am seeing a certain behaviour which I find strange, and am curious to get an
explanation to it. I have the following program.
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char ** argv) {
if(argc<2) {
return -1;
}
int value = atoi(argv[1]);
char * arr = new char[value];
// No segmentation fault unless next is an array.
char * next = new char[value];
int i = 0;
for(i=0; i<value; i++) {
arr = 'a';
next = 'a';
}
// NOTE: I am adding a char beyond the array boundary
arr='\0';
next='\0';
// This causes a segmentation fault
delete [] arr;
}
I compiled this with 3.2.2 on Red Hat Linux 9 on an Intel i686. When I run the
program, it gives me a Segmentation fault only when the array size is an odd
multiple of 4. My guess is it has something to do with word alignment. But, what
exactly is happening here?
Thanks for your help,
Vishal Grover
Developer
Trilogy Software Inc.