Getting core dump

Hi,

I am executing following code and getting coredump, can anybody expalin where is the problem...

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main()
{
char *s = "Life is beautiful", ch;
int len = strlen(s), start, end = -1, t = 0, length = 0, i;

printf("Original sentence=%s\n", s);
*(s + len + 1) = ' ';
*(s + len) = ' ';
while (*(s + length) != NULL) {
if (*(s + length) == ' ') {
start = end + 1;
end = length;
printf("%d %dn",start,end);
t = 0;
for (i = start; i < start + (end - start) / 2 + 1; i++) {
ch = *(s + i);
*(s + i) = *(s + end - t);
*(s + end - t) = ch;
t++;
}
}
length++;
}

printf("After processing=%s", s);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
char *s = "Life is beautiful";
// this is the same as writing
const char *s = "Life is breautiful";
// =>
*(s + len + 1) = ' '; // trying to change anyting s is pointing to will fail since it's const
// you have to create a char array:
char myArray[] = {"Life is beautiful"};
// and let s point to that
char* s = myArray;
// or well just use "myArray" to access the string

*(s + len + 1) = ' '; 
// this is in any way accessing not reserved memory (it's even behind "\0")
*(s + len) = ' ';
// This is overwriting your "\0" (if you were to print the string afterwards
// You would get "Life is beautiful " and then strange symbols until it finds a \0
Thank you so much Glandy...
If I wrote like this what will happen,

int main()
{
short i;

for(i=0;i>0;i++)
{
printf("I value is:%d\t",i);
}

}

I mean we are declaring

short i;

so short data type size is -32767 to 32767, is it abort of that size is over or still continuing that?
The Range of short is actually -32768 to 32767

However the binary representation of 32767 is the following:
hex: 0x7FFF => Binary: 01111111 11111111
since we have a "signed short" which means the first bit determines if it's a positive number or negative.
In the case above the first bit is 0 => positive number
1 would be negative number

If we do this:
1
2
3
4
5
6
7
short i = 32767;
i = i + 1;
// Let's look at this in binary:
// 01111111 11111111     (this is 32767)
// 00000000 00000001 +  (this is 1)
// 10000000 00000000 =  (this is a negative number since our first bit is 1 => -32768)
// so i would be now "-32768" 


You could say we kind of go in a loop.
When our short reaches 32767 and we add 1 we have -32768
Then we add a lot of numbers until we're again at 32767 and the next number would be
-32768 again

If you're not familiar with binary addition or overall representation of positive and negative numbers you should defintly look it up ^.^

I hope this makes sense to you =)
Last edited on
Hi Glandy,

Its very very good explanation and very much helpful.
Thank You very much.
Last edited on
Topic archived. No new replies allowed.