I am passing a char* to the function "reverse" and when I execute it with gdb I get:
Program received signal SIGSEGV, Segmentation fault.
0x000000000040083b in reverse (s=0x400b2b "hello") at pointersExample.c:72
72 *q = *p;
Attached is the source code.
I do not understand why this error occurs.
Why "modifyStruct" and "modifyString" are working right, but "reverse" does not work?
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book
{
char* title;
int pages;
float price;
};
void modifyInt (int *li)
{
*li *= 2;
}
void modifyStruct (struct book* lb)
{
char* newTitle = "The best book";
free(lb->title);
lb->title = malloc((strlen(newTitle) + 1) * sizeof(char));
strcpy(lb->title, newTitle);
lb->pages=350;
lb->price=20.25;
}
void modifyString (char* lw)
{
int i;
int strLen = strlen(lw);
for (i=0; i<strLen; i++)
if( (*(lw+i) >= 97) && (*(lw+i) <= 122) )
*(lw+i) -= 32; // Converts letters to upper case.
}
void reverse (char* s)
{
char* aux;
char* p;
char* q;
p = s;
int len = strlen(s);
aux = (char*) malloc ((len + 1) * sizeof(char));
printf("s=%s\n", s);
printf("strlen(s)=%d\n", len);
*(aux+len) = 0; // End string mark.
len--;
while (*p != 0)
{
*(aux+len) = *p;
len--;
p++;
}
printf("aux=%s\n", aux);
// Copy aux to s.
p = aux;
q = s;
while (*p != 0)
{
*q = *p;
p++;
q++;
}
printf("aux=%s\n", aux);
printf("s=%s\n", s);
}
int main()
{
int iv = 10;
struct book *mynewbook;
int len;
char* words1;
char* initial_words = "hello_pleased_to_met_you" ;
char* tmp = "hello";
printf ("\niv = %d\n", iv);
modifyInt(&iv);
printf ("After calling modifyInt, iv = %d\n\n", iv);
mynewbook = (struct book*)malloc (sizeof (struct book));
if (mynewbook == NULL)
return -1;
len = strlen("Unknown");
mynewbook->title = (char*) malloc ((len + 1) * sizeof(char));
strcpy(mynewbook->title, "Unknown");
mynewbook->pages=0;
mynewbook->price=0.0;
printf ("mynewbook: title = %s, pages=%d, price=%f\n",
mynewbook->title, mynewbook->pages, mynewbook->price);
modifyStruct(mynewbook);
printf ("After calling modifyStruct: mynewbook: title = %s, pages=%d, price=%f\n\n",
mynewbook->title, mynewbook->pages, mynewbook->price);
len = strlen(initial_words);
words1 = (char*) malloc ((len + 1) * sizeof(char));
strcpy(words1, initial_words);
printf ("words1 = %s\n", words1);
modifyString(words1);
printf ("After calling modifyString: words1 = %s\n\n", words1);
printf("tmp=%s\n" , tmp);
reverse(tmp);
printf("After calling reverse: tmp=%s\n\n" , tmp);
return 0;
}
You appear to be trying to alter a const string in the second loop.
Remember that this produces a const string: char* tmp = "hello";
if you change this to char tmp[] = "hello";
you will have a non-const string.