Home Man
Search
Today's Posts
Register

Post questions about C, C++, Java, SQL, and other programming languages here.

Segmentation fault when I pass a char pointer to a function in C.

Tags
programming

Login to Reply

 
Thread Tools Search this Thread
# 1  
Old 04-21-2018
Segmentation fault when I pass a char pointer to a function in C.

I am passing a char* to the function "reverse" and when I execute it with gdb I get:

Program received signal SIGSEGV, Segmentation fault.
Code:
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:

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;
}

Moderator's Comments:
Segmentation fault when I pass a char pointer to a function in C. Please use code tags

Last edited by jim mcnamara; 04-21-2018 at 09:29 AM..
# 2  
Old 04-21-2018
Code:
while (*p != 0)
  {
    *(aux+len) = *p;
    len--;[color=red]
    p++;[/red]
  }

You never set p back to the start of the string. I don't see where you call free() which you should learn to do. I just gave this code a quick look.

And therefore:

May I suggest something that will make your efforts easier?
There are several string functions that live in the
Code:
<string.h>

header file: strdup is one.
You should be using those functions, not rolling your own, given the way you have written your code.
Try:
Code:
more /usr/include/string.h

to locate some interesting library functions,
then read then man page for
Code:
strdup

and some other very helpful C library functions

Learn about strcpy, strstr, strchr, strdup - there are several other good ones to know, too. You decide.
# 3  
Old 04-21-2018
Thanks, but I want to understand pointers use and this is the reason that I do it with a pointer.

I have done new tests with this program and I have found that:

1) If tmp is declared and initialized in main so, it works right without changes in "reverse" function:

Code:
char* tmp;

  tmp = (char*) malloc ((strlen("hello") + 1) * sizeof(char));
  strcpy(tmp, "hello");
  printf("tmp=%s\n" , tmp);
  reverse(tmp);
  printf("After calling reverse: tmp=%s\n\n" , tmp);

The program prints:

Code:
tmp=hello
After calling reverse: tmp=olleh

2) If instead I do this:

Code:
char* tmp = "hello";

  printf("tmp=%s\n" , tmp);
  reverse(tmp);
  printf("After calling reverse: tmp=%s\n\n" , tmp);

Then I get the segmentation fault.

What is the difference?

In this second case, If I check the value of s in reverse, it is:
"hello" + 0 (end of string mark)


Moderator's Comments:
Segmentation fault when I pass a char pointer to a function in C. Seriously: Please use CODE tags as required by forum rules!

Last edited by RudiC; 04-21-2018 at 10:20 AM.. Reason: Added CODE tags.
# 4  
Old 04-21-2018
The initializer in char* tmp = "hello"; is a string constant. The C compiler is allowed to store string constants in read-only memory. If you want to overwrite a string, that string cannot be a string constant.
# 5  
Old 04-21-2018
you can't do that, because gcc places the literal "hello" of char* tmp = "hello" in a read-only data segment, but char tmp[] = "hello" not.
# 6  
Old 04-22-2018
I am scared of Don Cragun, because he knows everything ;-).

Quote:
you can't do that, because gcc places the literal "hello" of char* tmp = "hello" in a read-only data segment, but char tmp[] = "hello" not.
Yes, interesting. So because that array stores actual memory on the stack, you cannot change what it points to, hmmmm. I thought arrays were pointers, until I tried to assign an array (pointer) to something else ;-). [I mean the reverse, assign something else to that array].
# 7  
Old 04-22-2018
Quote:
Originally Posted by dryden
I am scared of Don Cragun, because he knows everything ;-).



Yes, interesting. So because that array stores actual memory on the stack, you cannot change what it points to, hmmmm. I thought arrays were pointers, until I tried to assign an array (pointer) to something else ;-). [I mean the reverse, assign something else to that array].
Don't be scared of me! I don't know everything, as I have unfortunately proven in earlier posts in this forum (but I do try to admit when I make mistakes).

Let me expand a little on what dodona and I have said in earlier posts...
Inside a function definition (such as in main() shown in post #1 in this thread), the declarations in main():
Code:
int main()
{
  int iv = 10;
  struct book *mynewbook;
  int len;
  char* words1;
  char* initial_words = "hello_pleased_to_met_you";
  char* tmp = "hello";
  ...
}

create:
  1. an integer named iv on the stack and initializes it to the value 10,
  2. a pointer named mynewbook that can be used to access a structure of type book but does not allocate any space for a structure of that type and the value assigned to that pointer will be any random value found on the stack where that pointer is located,
  3. an integer named len containing whatever random value is located on the stack at the address assigned to that integer,
  4. a pointer named words1 that can be used to access an object of type char that points to a random address depending on whatever value is located on the stack at the address assigned to that pointer,
  5. a pointer named initial_words that can be used to access an object of type char that points to the first character of the string "hello_pleased_to_met_you" which might be located in read-write memory on the stack, in read-only memory that is not located on the stack, or in read-write memory that is not located on the stack, and
  6. a pointer named tmp that can be used to access an object of type char that points to the first character of the string "hello" which might be located in read-write memory on the stack, in read-only memory that is not located on the stack, or in read-write memory that is not located on the stack.
With most modern compilers the strings mentioned in points 5 and 6 above will be located in read-only memory and will, therefore, generate a segmentation fault if you try to change the data in those strings.

Early C compilers (in the 1970's and 1980's) frequently put these arrays in read-write memory. And when you had code that tried to overwrite these strings, they succeeded. This had the side-effect of turning string constants into variables whose constant string values were not constants while the process was running.

To create an array of characters on the stack that can be read and written instead of a pointer on the stack that points to an array of characters that might be read-only, you need to use a declaration more like:
Code:
  char initial_words_array[25] = "hello_pleased_to_met_you";
  char tmp_array[6] = "hello";

Both of these create arrays of characters on the stack. The constant string initializers will be copied into these arrays (on the stack) every time the function is invoked.

Arrays of characters and pointers to characters are two very different things. An array of characters has a size that is the number of characters that can be stored in it. A pointer to a character (or a pointer to an array of characters) has a constant size (usually 4 bytes per pointer on a system with a 32-bit address space or 8 bytes per pointer on a system with a 64-bit address space). You can increment a pointer to point to the next element in the array to which it points. You can't increment an array (although you can increment elements of an array). Although an array name is not a pointer, C allows an array name used without following square brackets to be used as a synonym for the address of the first element of that array. So, if I had the declarations:
Code:
  char *tmp;
  tmp_array[6] = "hello";

then both of the following lines of code set the pointer tmp to point to the h in the string hello:
Code:
  tmp = &tmp_array[0];
  tmp = tmp_array;

To then update the pointer to point to the next character in the array, you can use any of the following lines of code:
Code:
  tmp++;
  ++tmp;
  tmp = tmp + 1;
  tmp = &tmp_array[1];
  tmp = tmp_array + 1

but you can't use either of:
Code:
  tmp = tmp_array++;
  tmp = ++tmp_array;

because tmp_array is an array; and an array is not a pointer type.
Login to Reply

« Previous Thread | Next Thread »
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
Segmentation fault in function call, shell script IB_88 Shell Programming and Scripting 1 04-23-2014 03:50 AM
Segmentation Fault femchi Homework & Coursework Questions 3 11-30-2012 10:59 PM
Using gdb, ignore beginning segmentation fault until reproduce environment segmentation fault pooyair Programming 6 10-13-2012 04:17 AM
Segmentation fault vincent__tse UNIX for Dummies Questions & Answers 2 08-29-2011 12:49 PM
segmentation fault while returning from function. er.rohan88 Programming 1 07-17-2010 01:11 AM
C++ segmentation fault while checking for null pointer vijaymrt Programming 3 02-21-2010 11:34 AM
segmentation fault in fwrite function ajaysahoo Programming 7 06-19-2009 11:33 AM
pass a pointer-to-pointer, or return a pointer? aaronwong Programming 11 01-08-2009 12:03 PM
Adding a single char to a char pointer. pallak7 Programming 5 12-06-2008 10:46 PM
Hi! segmentation fault vijlak Programming 4 11-13-2006 09:48 AM


All times are GMT -4. The time now is 01:01 AM.

Unix & Linux Forums Content Copyrightę1993-2018. All Rights Reserved.
UNIX.COM Login
Username:
Password:  
Show Password