1

The fork in the following code does not work! It never goes into run function. Can you please tell me what is wrong here?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void run(char* a)
{
    char* k=a;
    int i;
    for(i=0;i<3;i++)
      k[i]='s';
    printf("hi");
    return;
}
int main()
{   
    char* a="cbd";
    pid_t j;
    j=fork();
    printf("%d\t",j);
    int y;
    if(j==0)
      run(a);
    int i;
    for(i=0;i<3;i++)
      printf("%c\t",a[i]);
 return 0;
}

The output is

24180  c b d
smo
  • 167
  • 7

3 Answers3

4

Actually run() function is called. But the problem with k[i]='s'; statement. "cbd" is a string literal and read-only.

Allocate memory for string locally and pass the address.

like @Andy mentioned, child process crashed.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
1

The problem is with the k[i] = 's', which is causing the process to crash with a bus error. The reason is, you are trying to edit the string literal "cbd" which is placed in the RODATA section of the object file, which gets stored in read-only memory. If change the first line of main to char a[3] = {'c', 'b', 'd'}; your program works as expected.

Greg Prisament
  • 2,166
  • 1
  • 17
  • 18
  • I wouldn't suggest adding any object file terminology, it makes your answer confusing to the OP who is still learning basic `C` – tay10r Jul 10 '13 at 04:57
1

As for the fork(), there is no problem. It's your run() function. k is a pointer to a const string, so k[0]='s' tend to report access violation.

Manas
  • 598
  • 3
  • 14