Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault when assigning values to pointers in function

Long time listener, first time caller.

I do apologize if this problem has already been addressed (I imagine that is has been covered extensively), but I've searched through many questions about pointers and other seemingly related topics, but I still am unable to solve my problem.

I'm currently writing a string library for class project, and when I am getting a segmentation fault error when I try this:

#include "str2107.h"
#include <stdio.h>

void lstrip(char *s) {

        char *p, *q;
        p = q = s;

        while (*p == ' ' && *p != '\0') {
             *p++;
        }

        while (*p != '\0') {
            *q = *p;   //this is where the actual segmentation fault occurs.
            p++;
            q++;
        }

        *q = '\0';
}

My main program looks like this:

#include <stdio.h>
#include <stdlib.h>
#include "str2107.h"


int main(int argc, char** argv) {

    char *z1 = "      weeee";
    printf("lstrip function\n");
    printf("%s\n",z1);
    lstrip(z1);
    printf("%s\n",z1);

    return 0;
}
like image 503
CodyJamesCasey Avatar asked Oct 29 '13 15:10

CodyJamesCasey


People also ask

What causes segmentation fault with pointers?

A segmentation fault usually occurs when you try to access data via pointers for which no memory has been allocated. It is thus good practice to initialize pointers with the value NULL, and set it back to NULL after the memory has been released.

What are three kinds of pointers that can cause a segmentation fault?

The following are some typical causes of a segmentation fault: Attempting to access a nonexistent memory address (outside process's address space) Attempting to access memory the program does not have rights to (such as kernel structures in process context) Attempting to write read-only memory (such as code segment)

How do you fix a segmentation fault?

It can be resolved by having a base condition to return from the recursive function. A pointer must point to valid memory before accessing it.

Does dangling pointer cause segmentation fault?

If the memory has been reallocated to another process, then attempting to dereference the dangling pointer can cause segmentation faults (UNIX, Linux) or general protection faults (Windows).


2 Answers

z1 is pointing to a string literal and modifying a string literal is undefined behavior. Alternatively you can use the following declaration of z1 which will be modifiable:

char z1[] = "      weeee"; 

If we look at the C99 draft standard section 6.4.5 String literals paragraph 6 says(emphasis mine):

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

A few other points as WhozCraig points out this line:

while (*p == ' ' && *p != '\0') {

could be more succinctly written as:

while (*p == ' ' ) {

also you are using indirection here:

*p++;

but you don't actually use the resulting value, so you can change it to:

p++;
like image 157
Shafik Yaghmour Avatar answered Sep 22 '22 01:09

Shafik Yaghmour


When you write char *z1 = " weeee"; then z1 is a pointer that points to a memory that is in the code part, so you can't change it.

If you change it char z1[] = " weeee"; then z1 is an array of chars that are on the stack and you can change it.

If you had wrote char const *z1 = "..."; then it would be a compilation error, which is better and preferable over segmentation fault.

like image 41
Maroun Avatar answered Sep 21 '22 01:09

Maroun